简体   繁体   English

.NET Core 2.0分离Startup.cs服务注入

[英].NET Core 2.0 Separating Startup.cs Services Injection

So right now I got a project working with a N Tier architecture ( 3 layers: API, BL, DAL ). 所以现在我得到了一个使用N层架构的项目(3层:API,BL,DAL)。 My concern is that all the injection of my services happen in my Startup.cs file. 我担心的是我的所有服务注入都发生在我的Startup.cs文件中。

Is it possible to move them to the correct solution ? 是否有可能将它们转移到正确的解决方案?

EG Startup.cs ConfigureServices method EG Startup.cs ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
    {
        //MVC
        services.AddMvc();

        //Swagger
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Title = "2Commit Blogpost API",
                Version = "v1"
            });
        });
        services.ConfigureSwaggerGen(options =>
        {
            options.CustomSchemaIds(x => x.FullName);
        });

        //Mediatr
        services.AddScoped<IMediator, Mediator>();
        services.AddTransient<SingleInstanceFactory>(sp => sp.GetService);
        services.AddTransient<MultiInstanceFactory>(sp => sp.GetServices);
        services.AddMediatorHandlers(typeof(Startup).Assembly);

        //MongoDB
        services.Configure<MongoSettings>(s =>
        {
            s.Database = Configuration.GetSection("MongoConnection:Database").Value;
        });
        services.AddSingleton<IMongoClient, MongoClient>(client => new MongoClient(Configuration.GetSection("MongoConnection:ConnectionString").Value));

        //BL
        services.AddTransient<IUserService, UserService>();
        services.AddTransient<IAccountService, AccountService>();

        //DAL
        services.AddTransient<IRepository, MongoRepository>();

        //Authentication
        services.AddAuthentication()
            .AddJwtBearer(jwt =>
            {
                var signingKey =
                    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("Secret:Key").Value));

                jwt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,

                    ValidateIssuer = true,
                    ValidIssuer = "2CIssuer",

                    ValidateAudience = true,
                    ValidAudience = "2CAudience",

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero
                };
            });

        //Authorization
        services.AddAuthorization(auth =>
        {
            auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build());
        });
    }

Ideally, the "BL" part should move to my BL Solution, and the DAL & MongoDB part to my DAL solution. 理想情况下,“BL”部分应移至我的BL解决方案,DAL和MongoDB部分移至我的DAL解决方案。

How do I split it up? 我该如何拆分?

You should create BlStartupExtensions.cs in the root of your BL project, with the current lines: 您应该使用当前行在BL项目的根目录中创建BlStartupExtensions.cs

public static class BlStartupExtensions
{
    public static void ConfigureBlServices(this IServiceCollection services)
    {
        //register what you need
    }  
}

And then register it in your Startup.cs : 然后在Startup.cs注册它:

services.ConfigureBlServices();

With DAL, solution is absolutely the same. 使用DAL,解决方案绝对相同。

You could create extension in your relevant project like below. 您可以在相关项目中创建扩展,如下所示。

public static class DalServiceCollectionExtensions
{
    public static IServiceCollection AddDALDependencies(this IServiceCollection services, IConfigurationRoot configuration)
    {
        services.Configure<MongoSettings>(s =>
        {
            s.Database = configuration.GetSection("MongoConnection:Database").Value;
        });

        services.AddSingleton<IMongoClient, MongoClient>(
            client => new MongoClient(configuration.GetSection("MongoConnection:ConnectionString").Value));

        return services;
    }
}

Then you can add dependencies as below. 然后,您可以添加依赖项,如下所示。

public void ConfigureServices(IServiceCollection services)
{        
    services.AddDALDependencies(Configuration);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在startup.cs中注入所有服务,.net核心,重载 - inject all services in startup.cs, .net core, overloaded .net 核心 Startup.cs CreateScope 或 BuildServiceProvider - .net core Startup.cs CreateScope or BuildServiceProvider 如何修复 .NET Core 中 Startup.cs 类中的依赖注入错误 - How to fix the Dependency Injection error in Startup.cs class in .NET Core 在Startup.cs中生成角色在.NET Core 2.0中不再起作用 - Generating Roles in Startup.cs doesn't work anymore in .NET Core 2.0 关于 Startup.cs 添加服务时 ASP.NET Core 中 C# 模式的问题 - Question about C# Pattern in ASP.NET Core When Adding Services in Startup.cs Asp.Net核心中是否有任何可扩展性点,可以在startup.cs以外的任何地方注册服务? - Is there any extensibility point in Asp.Net core to register services anywhere other than startup.cs? 集成测试中的自定义 WebApplicationFactory 未在 Startup.cs 中注册服务(ASP.NET Core 3.1) - Custom WebApplicationFactory in integration testing not registering services in Startup.cs (ASP.NET Core 3.1) .NET Core program.cs 和 Startup.cs 未命中 - .NET Core program.cs and Startup.cs not hit 在ASP.NET CORE中的Startup.cs中设置动态变量 - Set Dynamic Variables in Startup.cs in ASP.NET CORE 在Startup.cs .net core 2.1中加载程序集 - Load assembly in Startup.cs .net core 2.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM