【问题标题】:.NET Core 2.0 Separating Startup.cs Services Injection.NET Core 2.0 分离 Startup.cs 服务注入
【发布时间】:2017-09-27 05:50:28
【问题描述】:

所以现在我有一个使用 N 层架构(3 层:API、BL、DAL)的项目。我担心的是我的所有服务注入都发生在我的 Startup.cs 文件中。

是否可以将它们移至正确的解决方案?

例如Startup.cs 配置服务方法

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());
        });
    }

理想情况下,“BL”部分应移至我的 BL 解决方案,而 DAL 和 MongoDB 部分应移至我的 DAL 解决方案。

如何拆分?

【问题讨论】:

    标签: c# asp.net-core .net-core


    【解决方案1】:

    您应该在 BL 项目的根目录中创建 BlStartupExtensions.cs,并使用当前行:

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

    然后在你的Startup.cs注册:

    services.ConfigureBlServices();
    

    使用 DAL,解决方案是完全一样的。

    【讨论】:

      【解决方案2】:

      您可以在您的相关项目中创建扩展,如下所示。

      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;
          }
      }
      

      然后你可以添加如下依赖。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-15
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多