I am using VS 2017 and .NET Core.
Using Dependency Injection, I would like to register my service at runtime, dynamically. My goal is to write instances of my service that implement the service interface inside of separate assemblies. The servicename/assembly name will then be added to some sort of configuration file (or db table).
My registration code would do something like this:
var ServiceTypeName = LoadServiceAssembly(AssemblyName);
var serviceProvider = new ServiceCollection()
.AddTransient<IDILogger, "ConsoleDILogger">() // <--- Goal
.BuildServiceProvider();
var logger = serviceProvider.GetService(IDILogger);
Clearly, the AddTransient line will not work as such a method does not exist. It does, however, depict the idea. I want to register the type by a string name so that the loader application need not be recompiled everytime I add a new service type.
I cannot seem to find how to do this. Any suggestions would be welcome.
TIA
You could read configured type from the settings, load the required type via reflection and register it in service collection:
// Read from config
var assemblyPath = "...";
var typeName = "...";
var assembly = Assembly.LoadFrom(assemblyPath);
var loggerType = assembly.GetType(typeName);
var serviceProvider = new ServiceCollection()
.AddTransient(typeof(IDILogger), loggerType)
.BuildServiceProvider();
var logger = serviceProvider.GetService<IDILogger>();
Such dynamic approach will not require any recompilation if you add or reconfigure new logger.
That's obviously not possible as is, however, I used something similar to this in a project to avoid having to add each new type to the container:
var assembly = typeof(YourClass).Assembly; // I actually use Assembly.LoadFile with well-known names
var types = assembly.ExportedTypes
// filter types that are unrelated
.Where(x => x.IsClass && x.IsPublic);
foreach (var type in types)
{
// assume that we want to inject any class that implements an interface
// whose name is the type's name prefixed with I
services.AddScoped(type.GetInterface($"I{type.Name}"), type);
}
For your specific case, you could even make this shorter:
var type = assembly.ExportedTypes.First(x => x.Name == runtimeName);
services.AddScoped(typeof(IDILogger), type);
A very genuine question and with references to different answers by users, here's how I have solved in .NET 6
In program.cs added the following
//Register Service Modules to DI
builder.Services.IncludeServiceModule(builder.Configuration);
The called static function contains something like this
public static class ServiceModule
{
public static IServiceCollection IncludeServiceModule(this IServiceCollection services,
IConfiguration configuration)
{
var appServices = System.Reflection.Assembly.Load("FMDeBill.Service").GetTypes().Where(s => s.Name.EndsWith("Service") && s.IsInterface == false).ToList();
foreach (var appService in appServices)
//services.AddTransient(appService.GetInterface($"I{appService.Name}"), appService);
services.Add(new ServiceDescriptor(appService, appService, ServiceLifetime.Scoped));
return services;
}
}
The assembly name is the name of the project/assembly with services. Any service that is not an interface and ends with "Service" such as "CategoryService" is registered dynamically.
Auto-Register Dependency Injected Services in .NET Core
I wrote this method to auto-register all your services and consumer interfaces and classes at runtime for Dependency Injection by the IoC Container in .NET. All you have to do is add your interfaces and/or concrete classes to the enums lists below and the RegisterServices() method will add them for dependency injection in your .NET application. You can then add them to constructors or call them for dependency injection by .NET.
I chose to load services from an enum rather than say a JSON or other configuration file for security reasons. It also reduces dependencies and also locks the applications state, as well as forces development to lock the app to compilation. Developers must modify, add, remove service types and keep them closely coupled to the code. Changing a configuration file is too dangerous!
LET'S BEGIN
You will need to create two files then change the Startup.cs file in .NET.
Create a file called ServiceList.cs in .NET. This one is just a couple enums where you can add your list of types you want registered as services or consumers of services. If you have many classes that inherit from an Interface, just add lists of those in services. But it will accept concrete types, as well. But if you add an interface, the RegisterServices method below will locate all the child classes that implement the interface and register those, as well. The RegisterServices() method will grab them and register all your services with the IoC in .NET for you.
// ADD SERVICES YOU WANT REGISTERED
enum ServicesList
{
ISampleService,
IAnotherService,
AConcreteClassService
}
// ADD CONSUMERS YOU WANT REGISTERED
enum ConsumersList
{
MyClass1,
MyClass2,
ISomeConsumerTypes
}
Create a second class file called RegisterServices.cs. Add the following code. This is the main method that registers all the services listed in the enums above. It is called RegisterServices.cs.
// REGISTER SERVICES
// This will pull all the services you added to the ServicesList.cs
// enum and try and register them with the Services Provider in .NET
static class RegisterServices
{
// You can add the Logger here if you like.
internal static void Start(IServiceCollection services, ILogger logger = null)
{
// Extract out all service enum values into a single list.
List<string> allTypesToAdd = new List<string>();
allTypesToAdd.AddRange(Enum.GetNames(typeof(ServicesList)).ToList());
allTypesToAdd.AddRange(Enum.GetNames(typeof(ConsumersList)).ToList());
// For now I am just getting the active running assembly
Assembly assembly = Assembly.GetExecutingAssembly();
IEnumerable<TypeInfo> assemblyTypes = assembly.DefinedTypes;
List<string> missingEnumTypes = new List<string>();
bool isTypeFound = false;
// Loop through all services in the collection.
// If your service type is not listed, add it.
foreach (string typeToAdd in allTypesToAdd)
{
// Verify the enum type to add to the service collection exists in the application.
isTypeFound = false;
foreach (TypeInfo type in assemblyTypes)
{
if (type.Name == typeToAdd)
{
if (type.IsInterface)
{
// Add the Interface and any concrete classes
// that are implementations of the parent interface.
var childOfInterface = assembly.GetTypes().Where(t => type.AsType().IsAssignableFrom(t));
foreach (Type c in childOfInterface)
{
if (typeToAdd != c.Name)
{
// For now this just assumes you need a request
// scoped service lifetime services. Change as needed.
services.TryAddScoped(type.AsType(), c);
logger?.LogInformation(LogEventIDs.Information_General_ID, "INFORMATION: A new Service Class Was Added: services.TryAddScoped(" + typeToAdd + "," + c.Name + ")");
}
}
} else {
// Only add the concrete class
// For now just use scoped service lifetime
services.TryAddScoped(type.AsType());
logger?.LogInformation(LogEventIDs.Information_General_ID, "INFORMATION: A new Service Class Was Added: services.TryAddScoped(" + typeToAdd + ")");
}
isTypeFound = true;
break;
}
}
// If users added types in the enum lists
// thats not found, flag as a warning!
if (!isTypeFound)
{
missingEnumTypes.Add(typeToAdd);
}
}
// If a bad enum service name was added, log that as a warning.
if (missingEnumTypes.Count > 0)
{
string items = string.Empty;
foreach (string s in missingEnumTypes)
{
if (items != string.Empty) items += " | ";
items += s;
}
logger?.LogWarning(LogEventIDs.Warning_General_ID, "WARNING: These Types/Interfaces/Classes added to Services were not found in the application >>> " + items);
}
}
}
Register Services consumes the enum list of Services and Consumers above.
The last step is to call the method above inside your Startup.cs .NET file in Core. Add RegisterServices.Start() static method call with your ConfigureServices class inside Startup.cs in the root of your .NET Core application. I also add the logger as a parameter but this version just use the services parameter. "services" is whatever the parameter is in your
ConfigureServices method in Startup.cs:
RegisterServices.Start(services);
HOW TO USE DEPENDENCY INJECTION
After you run RegisterServices in your .NET application and Startup.cs calls it, all your services (and child classes derived from interfaces) are now registered!
To call a Service and have it auto-implemented when you instantiate a class in .NET appears to be inconsistent. The IoC Container will auto-inject all constructor services in MVC Controllers, for example, but NOT regular classes. To solve that I recommend you try and inject everything into your controllers, then use the IServiceProvider in regular class constructors to help you auto-inject all other classes with the services they need (see below).
If you are in ASP.NET Core, your best strategy is to ALWAYS add each service to your controller's constructor using interfaces. You can then have full access to every service you need or any service a child object inside the controller might need. But there will be times you have classes you call outside the controllers that inject services but are not auto-injected. So below are some examples of how to do that and still honor the dependency injection model.
Note: If you are an expert at this, please suggest below in comments how I can improve on this idea, as this is the best model I have for now that is simple and easy to use.
// HOW TO USE SERVICES?
// CONTROLLERS (Web Applications)
// Always inject the services you need into the controller's constructor.
// The IoC Container in .NET always auto-injects these objects
// for you and are 100% ready to access. If using ASP.NET, always use the
// constructor of the controller to inject services.
public class HomeController : BaseController
{
private readonly ISampleService _myservice;
public HomeController(ISampleService myservice){
_myservice = myservice;
}
// You can now access your "_myservice" in any action method of the controller
}
// NON-CONTROLLERS and NON-INJECTED CONSTRUCTORS
// If you cant inject the service object into an ASP.NET Controller
// but still need to instantiate the object, your best alternative
// is to inject the ServiceProvider into your Controller or Class
// constructor first. IoC auto-injects the service collection
// so you can now access it to create child objects you can
// tell .NET to auto-inject with their own services when created
// using the registered services in your enum as an example.
public MyClass (IServiceProvider myservice) {
// Here are 3 ways to force the IoC to auto-inject your dependencies
var obj1 = myservice.GetService<SampleService>();
var obj2 = myservice.GetService(SampleService) as ISampleService;
var obj3 = myservice.GetRequiredService(SampleService) as ISampleService;
var obj4 = (SampleService)myservice.GetService(typeof(SampleService));
}
Below is one of the Service Interface types in the enum above and the child classes that got registered which are now available to use as services in the code above after running the RegisterServices call:
// SERVICE INTERFACE
public interface ISampleService
{
void Message(string message);
}
// SERVICE CONCRETE CLASS
class SampleService : ISampleService
{
public void Message(string message)
{
Console.WriteLine($"{message}");
}
}
// SERVICE CONCRETE CLASS
class AnotherSampleService : ISampleService
{
public void Message(string message)
{
Console.WriteLine($"{message}");
}
}
You can use factory to achieve that.
services.AddScoped(provider =>
{
//Resolve some service at runtime.
var aService = provider.GetService<AServiceType>();
//Any synchronous logic here
return new MyDynamicService();
});
Related
Similar to How to Inject Dependencies to Dynamically Loaded Assemblies, I want to inject dependencies into classes from dynamically loaded assemblies. Is this possible with the .NET 6.0 DI Container? If so, how? If not, is there a light-weight IOC container that can you might recommend? (Not adding a 2nd IOC system to the project would be preferred.)
(Note: there will be only 2-4 maximum possible dependencies to inject, so a fake injection system with if/switch statements could be acceptable.)
One challenge: ILogger<> typically expects a type, but the loading .dll has no compile-time knowledge of the types in the dynamically loaded assemblies, and vice-versa. I could use the non-generic ILogger interface, but am not sure if that works with DI.
EDIT:
Expanding example, as requested:
Given: All potential dependencies to inject come from the Microsoft.Extensions.Hosting nuget package. The two we initially expect to use are ILogging<> and IConfiguration.
Type desiredClass = <Type found in the dynamically loaded assembly>;
//The below line does not inject dependencies. I am trying to find out what will.
object classInstace = Activator.CreateInstance(desiredClass);
MethodInfo selectedMethod = desiredClass.GetMethods
.Single(m=>m.Name=="Execute" && m.GetParameters().All(p=>p.IsOptional));
//Schedule the method in HangFire
RecurringJob.AddOrUpdate(
() => selectedMethod!.Invoke(
ClassInstance,
Array.Empty<object?>(),
scheduleForThisTask);
I found a very ugly way to get this done, and very much hope there is a cleaner way to accomplish this. (Please let there be a built-in way to do this that I have missed.)
Create an extension method GetInjectedObject for IService Provider:
public static object GetInjectedObject(this IServiceProvider serviceProvider, Type type)
{
//Dependency injection the ugly way
//Find the constructor that asks for the most injected parameters
var constructor = type.GetConstructors().Where(cn =>
cn.GetParameters().All(par => serviceProvider.GetServices(par.ParameterType).Any()))
.OrderByDescending(cn => cn.GetParameters().Length).FirstOrDefault();
if (null == constructor)
throw new Exception($"Type {type.Name} does not have a constructor without non-injectible parameters.");
//Get the needed parameters from the IServiceProvider
var constructorParameters =
constructor.GetParameters().Select(par => serviceProvider.GetService(par.ParameterType)).ToArray();
//Create the object with the parameters
var classInstance = Activator.CreateInstance(type, constructorParameters);
return classInstance;
}
and then create the objects like this:
_classInstance = serviceProvider.GetInjectedObject(Class);
Perhaps I misunderstood the problem, might it work for you to:
Have an assembly shared by the loading assembly (i.e. your Composition Root) and the dynamically loaded assembly? This assembly could contain an interface that dynamically loaded types must implement. (you might already have a shared assembly)
Load the dynamically loaded assembly at startup at the point that you're still wiring the DI Container?
In that case I expect an interface similar to:
namespace MySharedAssembly
{
public interface ITask
{
void Execute(TaskSchedule schedule);
}
public class TaskSchedule { ... }
}
In the dynamically loaded assembly:
namespace MyDynamicAssembly
{
public class HelloWorldTask : ITask
{
public void Execute(TaskSchedule schedule)
{
Console.WriteLine("Hello world!");
}
}
}
By doing so, you can:
Easily find all types in the dynamically loaded assembly by the ITask interface.
Register them by their concrete type in the DI Container.
Resolve them by their concrete type when needed, while their dependencies are injected by the DI Container.
For instance:
string dynamicallyLoadedAssemblyPath = "c:\\...\etc\etc\myAssembly.dll";
// Load plugin assembly
Assembly assembly =
Assembly.Load(AssemblyName.GetAssemblyName(dynamicallyLoadedAssemblyPath));
// Load plugin types
Type plugins = assembly.GetExportedTypes().Where(typeof(ITask).IsAssignableFrom);
// Register plugins in DI Container
foreach (var plugin in plugins)
{
services.AddTransient(plugin, plugin);
}
// Add jobs after container was constructed
IServiceProvider provider = ...
foreach (var plugin in plugins)
{
var scheduleForThisTask = GetSchedule(plugin);
RecurringJob.AddOrUpdate(() =>
{
// It might be important to execute each task in its own scope.
using (var scope = provider.CreateScope())
{
var task = (ITask)scope.ServiceProvider.GetRequiredService(plugin);
task.Execute(scheduleForThisTask);
}
}
}
I'm wondering how to deal with dependency injection in ASP.NET Core
for types that have both objects and strings as parameters. As strings can't be registered to the DI framework I'm
currently using an implementationfactory and use the service locator
pattern, is there another way ? Is there something like Autofac's .WithParamenter for named parameters ?
Asp.net core DI makes it easy (and clean) to register a type to the DI framework for types with arguments that are already registered to the DI framework.
Given the following three constructors :
public MyStateService() { /* .... */ }
public MyServiceBackend(IMyStateService state) { /* .... */}
public MyServiceClient(IMyStateService state, IMyServiceBackend backend, string logConfigPath) { /*.... */ }
The first two types are easily registered to the DI container as follows :
services.AddScoped<IMyStateService , MyStateService>();
services.AddScoped<IMyServiceBackend, MyServiceBackend>();
For the third however, I had to use an implementationfactory and use the service locator pattern to get the first two types to inject.
services.AddScoped<IMyServiceClient, MyServiceClient>((ctx) =>
{
IMyStateService state= ctx.GetRequiredService<IMyStateService >();
IMyServiceBackend backend = ctx.GetRequiredService<IMyServiceBackend>();
return new MyServiceClient(state, backend, _serilogConfigPath);
});
My technical project goes nuts on seeing a service locator [anti-pattern ] and demands a solution without service locator.
If we were using Autofac we could use the .WithParameter() for named parameters, but dotnet core di doesn't have that, does it ?
Is there another elegant way ?
Take advantage of ActivatorUtilities,
public static T CreateInstance<T> (IServiceProvider provider, params object[] parameters);
Which
Instantiate a type with constructor arguments provided directly and/or from an IServiceProvider.
//...
services.AddScoped<IMyServiceClient, MyServiceClient>((provider) => {
return ActivatorUtilities.CreateInstance<MyServiceClient>(provider, _serilogConfigPath);
});
//...
In the above example the provider will be used to resolve the other dependencies while string parameter will be provided directly.
If the target class can be refactored then do not explicitly depend on the string. Consider using the Options pattern
Reference: Options pattern in ASP.NET Core
Create a concrete class to store the desired data
public class LogConfigOPtions {
public string Path { get; set; }
}
Refactor the target class to depend on that
//...
string string logConfigPath;
//ctor
public MyServiceClient(IMyStateService state, IMyServiceBackend backend, IOptions<LogConfigOPtions> options) {
logConfigPath = options.Value.Path;
//...
}
And finally, configure options accordingly when registering services
//...
services.Configure<LogConfigOPtions>(option => {
option.Path = _serilogConfigPath;
});
services.AddScoped<IMyServiceClient, MyServiceClient>();
services.AddScoped<IMyStateService , MyStateService>();
services.AddScoped<IMyServiceBackend, MyServiceBackend>();
//...
I want to implement dependency injection in ASP.NET CORE 1. I know everything is about DI in .Net Core. For example
public void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddTransient<IDateTime, SystemDateTime>();
}
But for Big projects which has more than 20 entities and Services, it is so difficult and unreadable writing all of these code lines inside ConfigureServices. I want to know Is this possible implement dependency injection outside of Startup.cs and then add it to services.
Thanks for answers.
you can write extension methods of IServiceCollection to encapsulate a lot of service registrations into 1 line of code in Startup.cs
for example here is one from my project:
using cloudscribe.Core.Models;
using cloudscribe.Core.Models.Setup;
using cloudscribe.Core.Web;
using cloudscribe.Core.Web.Components;
using cloudscribe.Core.Web.Components.Editor;
using cloudscribe.Core.Web.Components.Messaging;
using cloudscribe.Core.Web.Navigation;
using cloudscribe.Web.Common.Razor;
using cloudscribe.Web.Navigation;
using cloudscribe.Web.Navigation.Caching;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using System.Reflection;
using Microsoft.AspNetCore.Authorization;
namespace Microsoft.Extensions.DependencyInjection
{
public static class StartupExtensions
{
public static IServiceCollection AddCloudscribeCore(this IServiceCollection services, IConfigurationRoot configuration)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.Configure<MultiTenantOptions>(configuration.GetSection("MultiTenantOptions"));
services.Configure<SiteConfigOptions>(configuration.GetSection("SiteConfigOptions"));
services.Configure<UIOptions>(configuration.GetSection("UIOptions"));
services.Configure<CkeditorOptions>(configuration.GetSection("CkeditorOptions"));
services.Configure<CachingSiteResolverOptions>(configuration.GetSection("CachingSiteResolverOptions"));
services.AddMultitenancy<SiteContext, CachingSiteResolver>();
services.AddScoped<CacheHelper, CacheHelper>();
services.AddScoped<SiteManager, SiteManager>();
services.AddScoped<GeoDataManager, GeoDataManager>();
services.AddScoped<SystemInfoManager, SystemInfoManager>();
services.AddScoped<IpAddressTracker, IpAddressTracker>();
services.AddScoped<SiteDataProtector>();
services.AddCloudscribeCommmon();
services.AddScoped<ITimeZoneIdResolver, RequestTimeZoneIdResolver>();
services.AddCloudscribePagination();
services.AddScoped<IVersionProviderFactory, VersionProviderFactory>();
services.AddScoped<IVersionProvider, CloudscribeCoreVersionProvider>();
services.AddTransient<ISiteMessageEmailSender, SiteEmailMessageSender>();
services.AddTransient<ISmsSender, SiteSmsSender>();
services.AddSingleton<IThemeListBuilder, SiteThemeListBuilder>();
services.TryAddScoped<ViewRenderer, ViewRenderer>();
services.AddSingleton<IOptions<NavigationOptions>, SiteNavigationOptionsResolver>();
services.AddScoped<ITreeCacheKeyResolver, SiteNavigationCacheKeyResolver>();
services.AddScoped<INodeUrlPrefixProvider, FolderTenantNodeUrlPrefixProvider>();
services.AddCloudscribeNavigation(configuration);
services.AddCloudscribeIdentity();
return services;
}
}
}
and in Startup.cs I call that method with one line of code
services.AddCloudscribeCore(Configuration);
There are several approaches that can be taken, but some are simply moving code between classes; I suggest you consider Assembly Scanning as I describe as the second option below:
1. 'MOVE THE PROBLEM': EXTENSION METHODS
The initial option is to use extension methods for configuration of Services.
Here is one example that wraps multiple service reigstrations into one extension method:
public static IServiceCollection AddCustomServices(this IServiceCollection services)
{
services.AddScoped<IBrowserConfigService, BrowserConfigService>();
services.AddScoped<IManifestService, ManifestService>();
services.AddScoped<IRobotsService, RobotsService>();
services.AddScoped<ISitemapService, SitemapService>();
services.AddScoped<ISitemapPingerService, SitemapPingerService>();
// Add your own custom services here e.g.
// Singleton - Only one instance is ever created and returned.
services.AddSingleton<IExampleService, ExampleService>();
// Scoped - A new instance is created and returned for each request/response cycle.
services.AddScoped<IExampleService, ExampleService>();
// Transient - A new instance is created and returned each time.
services.AddTransient<IExampleService, ExampleService>();
return services;
}
This can be called within ConfigureServices:
services.AddCustomServices();
Note: This is useful as a 'builder pattern', for specific configurations (for example, when a service needs multiple options to be passed to it), but, does not solve the problem of having to register multiple services by hand coding; it is essentially no different to writing the same code but in a different class file, and it still needs manual maintenance.
2. 'SOLVE THE PROBLEM': ASSEMBLY SCANNING
The 'best practice' option is Assembly Scanning which is used to automatically find and Register components based on their Implemented Interfaces; below is an Autofac example:
var assembly= Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
One trick to handle lifetime (or scope) of registration, is to use a marker interface (an empty interface), for example IScopedService, and use that to scan for and register services with the appropriate lifetime. This is the lowest friction approach to registering multiple services, which is automatic, and therefore 'zero maintenance'.
Note: The built in ASP.Net Core DI implementation does not support Assembly Scanning (as pf current, 2016 release); however, the Scrutor project on Github (and Nuget) adds this functionality, which condenses Service and Type registration to:
var collection = new ServiceCollection();
collection.Scan(scan => scan
.FromAssemblyOf<ITransientService>()
.AddClasses(classes => classes.AssignableTo<ITransientService>())
.AsImplementedInterfaces()
.WithTransientLifetime()
.AddClasses(classes => classes.AssignableTo<IScopedService>())
.As<IScopedService>()
.WithScopedLifetime());
SUMMARY:
Assembly Scanning, in combination with Extension Methods (where applicable) will save you a considerable amount of maintenance, and is performed once at application startup, and subsequently cached. It obviates the need to hand code service registrations.
You can write an extension method for batch registration:
public static void AddScopedFromAssembly(this IServiceCollection services, Assembly assembly)
{
var allServices = assembly.GetTypes().Where(p =>
p.GetTypeInfo().IsClass &&
!p.GetTypeInfo().IsAbstract);
foreach (var type in allServices)
{
var allInterfaces = type.GetInterfaces();
var mainInterfaces = allInterfaces.Except
(allInterfaces.SelectMany(t => t.GetInterfaces()));
foreach (var itype in mainInterfaces)
{
services.AddScoped(itype, type); // if you want you can pass lifetime as a parameter
}
}
}
And usage:
services.AddScopedFromAssembly(assembly);
Add DependenciesManager class to your project and implement AddApplicationRepositories method.
public static class DependenciesManager
{
public static void AddApplicationRepositories(this IServiceCollection service)
{
var assembly = Assembly.GetExecutingAssembly();
var services = assembly.GetTypes().Where(type =>
type.GetTypeInfo().IsClass && type.Name.EndsWith("Repository") &&
!type.GetTypeInfo().IsAbstract);
foreach (var serviceType in services)
{
var allInterfaces = serviceType.GetInterfaces();
var mainInterfaces = allInterfaces.Except
(allInterfaces.SelectMany(t => t.GetInterfaces()));
foreach (var iServiceType in mainInterfaces)
{
service.AddScoped(iServiceType, serviceType);
}
}
}
}
In Startup class add services.AddApplicationRepositories(); in ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationRepositories();
}
In case you need to register different services, just implement more methods in DependenciesManager class. For example, if you need to register some Authorization Handler services, just implement AddAuthorizationHandlers method:
public static void AddAuthorizationHandlers(this IServiceCollection service)
{
var assembly = Assembly.GetExecutingAssembly();
var services = assembly.GetTypes().Where(type =>
type.GetTypeInfo().IsClass && type.Name.EndsWith("Handler") &&
!type.GetTypeInfo().IsAbstract);
foreach (var serviceType in services)
{
var allInterfaces = serviceType.GetInterfaces();
var mainInterfaces = allInterfaces.Except
(allInterfaces.SelectMany(t => t.GetInterfaces()));
foreach (var iServiceType in mainInterfaces)
{
service.AddScoped(iServiceType, serviceType);
}
}
}
And in Startup class add:
services.AddAuthorizationHandlers();
Notes: the names of the services and its implementation you want to register must end with "Repository" or "Handler" according to my answer.
I recently implemented the Assembly scanning approach (successfully), but in the end found the cluster_registrations_in_a_few_extension_methods approach a lot clearer to read for myself and for other programmers working on it.
If you keep the clustering of registrations close to where the registered classes are defined, maintenance is always a lot less work than the maintenance involved with the registered classes themselves.
We have a Web API project and using the Autofac Web API Integration as the IoC container. The code that we use to register all of our types is as follows:
public class CompositionRootConfigurator
{
public static AutofacWebApiDependencyResolver Configure(Assembly servicesAssembly)
{
var container = BuildContainer(servicesAssembly);
var resolver = new AutofacWebApiDependencyResolver(container);
return resolver;
}
public static IContainer BuildContainer(Assembly servicesAssembly)
{
/*TO DELETE ONCE THE REFERENCES ISSUE IS RESOLVED!*/
var dummy = new EmployeesBL(new ContextFactory(new DBContextFactory(new RoleBasedSecurity(), new Identity())));
var builder = new ContainerBuilder();
if (servicesAssembly != null) // this is a temporary workaround, we need a more solid approach here
{
builder.RegisterApiControllers(servicesAssembly);
}
/* Registers all interfaces and their implementations from the following assemblies in the IoC container
* 1. CB.CRISP.BL
* 2. CB.CRISP.BL.CONTRACTS
* 3. CB.CRISP.DAL
* 4. CB.CRISP.DAL.CONTRACTS
* The current assembly is excluded because the controllers were registered with the builder.RegisterApiControllers expression above.
*/
var appAssemblies = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.ToString().StartsWith("CB.CRISP"))
.ToArray();
builder.RegisterAssemblyTypes(appAssemblies).AsImplementedInterfaces();
if (servicesAssembly != null)
{
builder.RegisterAssemblyTypes(servicesAssembly).AsImplementedInterfaces();
}
return builder.Build();
}
}
Now suppose we have a MyType which implements IMyType and this is the only one that must be a single instance per request and it will be injected in several objects along the hierarchy.
I am at a loss in how to specify this within this existing code. If I just go ahead and just do
builder.RegisterType<MyType>()
.As<IMyType>()
.InstancePerRequest();
since it will also be registered with all the others Will one registration overwrite the other one, will they be duplicated, are there potential problems?
Thank you for your insight.
Autofac will override the first registration and will accept the last one. Here is more detail.
So you should register MyType after registering all type.
I haven't seen any potential problem of this.
But you can register all types like this to be sure.
builder.RegisterAssemblyTypes(servicesAssembly).Except<MyType>().AsImplementedInterfaces();
Here is more detail about scanning.
I'm trying to create LinFu interceptors for all methods in my DAL assembly. While I can do something like this:
[Intercepts(typeof(IFirstRepository))]
[Intercepts(typeof(ISecondaryRepository))]
[Intercepts(typeof(IIAnotherRepository))]
public class DalInterceptor : IInterceptor, IInitialize
{
...
}
that's getting quite messy and needs manual updating every time a new repository is added to the assembly.
Is there a way to automatically create a proxy class for each type in the assembly?
UPDATE:
I've updated my proxy builder using the suggestion from the author himself (Mr Laureano) so I now have this:
Func<IServiceRequestResult, object> createProxy = request =>
{
var proxyFactory = new ProxyFactory();
DalInterceptor dalInterceptor = new DalLiteInterceptor();
return proxyFactory.CreateProxy<object>(dalInterceptor);
};
The interceptor is set up as before. The issue I'm having now is that the proxy object doesn't include the constructors and methods of the original object (I'm guessing as I'm using object in the generic create method).
Do I just cast this back to the required type or am I doing something fundamentally wrong?
Thanks.
It looks like you're trying to use LinFu's IOC container to intercept various services that are instantiated by the container. It turns out that LinFu has an internal class called ProxyInjector that lets you decide which services should be intercepted and how the proxy for each service instance should be created. Here's the sample code:
Func<IServiceRequestResult, bool> shouldInterceptServiceInstance = request=>request.ServiceType.Name.EndsWith("Repository");
Func<IServiceRequestResult, object> createProxy = request =>
{
// TODO: create your proxy instance here
return yourProxy;
};
// Create the injector and attach it to the container so that you can selectively
// decide which instances should be proxied
var container = new ServiceContainer();
var injector = new ProxyInjector(shouldInterceptServiceInstance, createProxy);
container.PostProcessors.Add(injector);
// ...Do something with the container here
EDIT: I just modified the ProxyInjector class so that it is now a public class instead of an internal class in LinFu. Try it out and let me know if that helps.