简体   繁体   中英

How to avoid Registering a service in startup.cs

In asp.net core we have to register service in order to use it but when services increases what we have to do? just like the code below i just have ShopService what if i have more then 50 services.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddDbContext<SGAContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("SGAContext")));
    services.AddScoped<DbContext, SGAContext>();
    services.AddScoped<IShopService, ShopService>();
}

What is the best way to minimize this situation.

You can add your services using certain criteria and reflection, like below:

public static IServiceCollection AddScopedImplementations<T>(this IServiceCollection services)
{
    var types = typeof(T).Assembly.GetTypes().Where(_ => !_.IsAbstract && _.IsClass && typeof(T).IsAssignableFrom(_));

    foreach (var t in types)
        services.AddScoped(t);

    return services;
}

The idea of AddScopedImplementations method is to add all types that are implementing certain interface

I'm scanning the same assembly that has interface implemented within.

Then to get all types that implement interface Startup.ConfigureServices can be modified like

services.AddScopedImplementations<IConverterToDb>();
services.AddScopedImplementations<IMapperLink>();

It scans assembly that has IConverterToDb interface and registers all IConverterToDb implementations that are not abstract

You can use the same approach with interface-type registrations, like empty IScopedServiceToBeAdded or mark your service types with attribute to implement automatic services.AddScoped<IShopService, ShopService>() registrations

public interface IShopService : IAutoRegistration
{}
public interface ShopService : IShopService
{}

then you can scan for all interfaces derived from IAutoRegistration (like IShopService and use this list to find types that implement derived interfaces ShopService

then you can put found interface - class pairs to the services.AddScoped(tinterface, tclass)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM