You can easily implement your own method of registering all types of assemblies for a given assembly or set of assemblies ... the code will correspond to the lines:
foreach (var implementationType in assemblies.SelectMany(assembly => assembly.GetTypes()).Where(type => !type.GetTypeInfo().IsAbstract)) { foreach(var interfaceType in implementationType.GetInterfaces()) { services.AddSingleton(interfaceType, implementationType); } }
The code selects all non-abstract types from assemblies and extracts all the interfaces for each type, creating a Singleton registration for each interface / implementation pair.
I prefer to register all instances of the explicit interface (i.e., ICommandHandler or similar), so I add extension methods along the AddCommandHandlers lines shown below for several types that I want any instance to be registered ...
public static void AddCommandHandlers(this IServiceCollection services, params Assembly[] assemblies) { var serviceType = typeof(ICommandHandler); foreach (var implementationType in assemblies.SelectMany(assembly => assembly.GetTypes()).Where(type => serviceType.IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)) { services.AddSingleton(serviceType, implementationType); } }
Adding a call like services.AddCommandHandlers(DomainAssembly.Reference); in ConfigureServices ...
I prefer this approach because registering all interfaces for all types will add a lot of hard registrations to your IoC container ... this is usually not a huge deal, but cleaner in my opinion.
Chris baxter
source share