gpt4 book ai didi

c# - 共享启动配置 dotnet core 2 WebAPI

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:24 25 4
gpt4 key购买 nike

在具有多个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com