共享启动配置dotnet核心2 WebAPI

问题描述 投票:1回答:1

在处理具有多个API的项目时,我们希望共享配置以确保每个API具有相同的记录器配置等,并且我们可以将所有nuget包保留在Extensions类Project中。

使用扩展来实现这一点,是实现共享启动配置的好方法吗?有没有更好的办法?

扩展类。

namespace Extensions
{
    public static class Extensions
    {
        public static IServiceCollection AddExtensionsConfig(this IServiceCollection services)
        {
            services.AddLoggerConfig();
            services.AddMvc();

            return services;
        }

        public static IApplicationBuilder UseExtensionsConfig(this IApplicationBuilder app)
        {
            //use logger
            app.UseLoggerConfig();

            // auth
            app.UseAuthentication();

            // set startup file to index.html for easy testing
            app.UseDefaultFiles();

            //enable CORS
            app.UseCorsConfig();

            //added support for static file
            app.UseStaticFiles();

            app.UseMvc();

            return app;
        }
    }
}

记录器扩展

namespace Extensions.Logger
{
    public static class LoggerServiceExtensions
    {
        public static IServiceCollection AddLoggerConfig(this IServiceCollection services)
        {
            //serilog
            services.AddLogging(loggingBuilder =>
             loggingBuilder.AddSerilog(dispose: true));

            var loggerServices = new ServiceCollection()
               .AddLogging(builder =>
               {
                   builder.AddSerilog();
               });

            return services;
        }

        public static IApplicationBuilder UseLoggerConfig(this IApplicationBuilder app)
        {
            //add serilog https://github.com/serilog/serilog-extensions-logging
            // https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
            Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();

            var startTime = DateTimeOffset.UtcNow;

            Log.Logger.Information("Started at {StartTime} and 0x{Hello:X} is hex of 42", startTime, 42);

            return app;
        }
    }
}

然后在Startup ConfigureServices中

// add config
services.AddExtensionsConfig();

和启动配置方法

// use config
app.UseExtensionsConfig();
c# .net-core shared-libraries asp.net-core-webapi
1个回答
1
投票

使用扩展来实现这一点,是实现共享启动配置的好方法吗?有没有更好的办法 ?

目前这是建议的方法。您还将在提供的大多数示例中看到此模式,并使用第三部分扩展。 asp.net-core的模块化特性允许这种首选方法

© www.soinside.com 2019 - 2024. All rights reserved.