在具有多个 API 的项目上工作,我们希望共享配置以确保每个 API 具有相同的记录器配置等,并且我们可以将所有 nuget 包保留在扩展类项目中。
使用扩展来实现,是实现共享启动配置的好方法吗?有没有更好的办法?
扩展类。
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();
最佳答案
Using extensions to achieve this, is good way to achieve a shared startup configuration ? Is there a better way ?
这是目前推荐的方法。您还将在提供的大多数示例和第三部分扩展中看到这种模式。 asp.net-core 的模块化特性允许这种首选方法
关于c# - 共享启动配置 dotnet core 2 WebAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49087210/