Does ASP.Net Core built-in Dependency Injection feature support auto registration of services? I don't want to regester them manually like this:
services.Add(new ServiceDescriptor(typeof(IUserService),
new UserService(new AtmDbContext())));
For my project the following helped me:
In Startup.cs method ConfigureServices add row:
services.AddHandlers("Project name");
And implementation of that:
public static IServiceCollection AddHandlers(this IServiceCollection services, string assemblyName)
{
var assemblyPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), assemblyName + ".dll");
var assembly = Assembly.Load(AssemblyLoadContext.GetAssemblyName(assemblyPath));
var classTypes = assembly.ExportedTypes.Select(t => IntrospectionExtensions.GetTypeInfo(t)).Where(t => t.IsClass && !t.IsAbstract);
foreach (var type in classTypes)
{
var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo());
foreach (var handlerType in interfaces.Where(i => i.IsGenericType))
{
services.AddTransient(handlerType.AsType(), type.AsType());
}
}
return services;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With