Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does DependencyInjection support auto registration of services?

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())));
like image 338
Arsen Avatar asked Dec 10 '15 09:12

Arsen


1 Answers

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;
}
like image 144
A. Gladkiy Avatar answered Nov 14 '22 22:11

A. Gladkiy