asp.net-coredependency-injectiondependenciesdependency-management

How do I automatically add my service registration to the di container


I want to automate adding services to di container. Here in my ServiceRegistration class:

builder.Services.AddScoped<ICategoryService, CategoryService>();
builder.Services.AddScoped<IProductDetailService, ProductDetailService>();
builder.Services.AddScoped<IProductImageService, ProductImageService>();
builder.Services.AddScoped<IProductService, ProductService>();
...

I don't want to add like this, I want to mark each of my service classes with an attribute and find this class and find the interface that the class I found implements and add it to di container automatically. How do I do this? Or do you have a better solution?

I don't want to add my services manually, I want to do it automatically


Solution

  • You can use Reflection:

    var components =
        from type in typeof(CategoryService).Assembly.GetTypes()
        where type.Name.EndsWith("Service")
        where !type.IsAbstract && !type.IsGenenicTypeDefinition
        where type.GetInterfaces().Count() == 1
        select { Service = type.GetInterfaces().Single(), Implementation = type };
    
    foreach (var component in components)
    {
        services.AddScoped(component.Service, component.Implementation);
    }
    

    There are also extensions to MS.DI available that can simplify this task, such as Scrutor.