有没有办法减少 ASP.NET core 中 Startup 类的服务注入次数?

Isa*_*ika 0 c# dependency-injection asp.net-core asp.net-core-3.1

我正在使用 .net core 开发一个 API,并且即将使用依赖注入,但我意识到ConfigureServices(IServiceCollection services)Startup 类中的方法被服务注入堵塞是我不喜欢的。例如...

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
        services.AddScoped<IServiceOne, ServiceOne>();
        services.AddScoped<IServiceTwo, ServiceTwo>();
        services.AddScoped<IServiceThree, ServiceThree>();
        services.AddScoped<IServiceFour, ServiceFour>();
        //more and more services. This could go on and on and that would make the whole class ugly
    }
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以将所有这些服务放在一个类中并在 Startup 类中调用它们?我使用的是asp.net3.1。

谢谢。

Pan*_*vos 6

AddDbContext是一种扩展方法,用于配置和注册DbContext派生类IServicesCollection。您可以使用相同的模式并创建自己的扩展方法来添加特定服务,例如:

static class MyExtensions
{
    static IServiceCollection AddMyServices(this IServiceCollection services)
    {
        services.AddScoped<IServiceOne, ServiceOne>();
        services.AddScoped<IServiceTwo, ServiceTwo>();
        services.AddScoped<IServiceThree, ServiceThree>();
        services.AddScoped<IServiceFour, ServiceFour>();

        return services;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以根据应用程序的模块或场景将注册拆分为相关服务,例如,AddAccounting将特定模块所需的所有注册放在一个位置,例如:AddInventory

static IServiceCollection AddAccounting(this IServiceCollection services)
{
    var connection=Configuration.GetConnectionString("MyConnection");
    services.AddDbContext<Account>(options => options.UseSqlServer(connection));
    services.AddDbContext<Transaction>(options => options.UseSqlServer(connection));
    services.AddScoped<IServiceOne, ServiceOne>();
    services.AddScoped<IServiceTwo, ServiceTwo>();

    return services;
}

static IServiceCollection AddInventory(this IServiceCollection services)
{
    var connection=Configuration.GetConnectionString("MyConnection");
    services.AddDbContext<Warehouse>(options => options.UseSqlServer(connection));
    services.AddDbContext<Product>(options => options.UseSqlServer(connection));
    services.AddScoped<IServiceThree, ServiceThree>();

    return services;
}
Run Code Online (Sandbox Code Playgroud)