每个请求加载不同的配置
Loading different piece of configuration every request
我有一个应用程序,我想根据来自请求的 header 加载不同的配置部分
这是我的一部分 startup.cs
public void ConfigureServices(IServiceCollection 服务)
{
services.AddControllers();
IConfiguration cfg = null;
services.AddScoped<IConfiguration>(x =>
{
cfg = Configuration.GetSection("AppSettings:" + x.GetService<IHttpContextAccessor>()?.HttpContext?.Request?.Headers["xxx"]);
return (cfg);
});
services.AddSingleton<DB.Calendar.Repo>(x => new DB.Calendar.Repo(cfg));
services.AddApplicationInsightsTelemetry();
}
问题是根本没有调用 AddScoped 的 lambda(即使我只是放了一些 console.outs)所以 cfg 保持为空。我做错了什么
传递给 services.AddScoped()
的委托仅在创建新范围时执行(即在 ASP.NET 应用的 HTTP 请求开始时)。这解释了为什么在调用 AddSingleton()
时 cfg
是 null
。
像这样的东西应该可以工作:
services.AddScoped<DB.Calendar.Repo>(x => {
var cfg = Configuration.GetSection("AppSettings:" + x.GetService<IHttpContextAccessor>()?.HttpContext?.Request?.Headers["xxx"]);
return new DB.Calendar.Repo(cfg);
});
一旦你让它工作,明智的做法是将读取正确配置部分的逻辑移动到它自己的服务中,以使其更易于测试(并使其看起来干净)。
我有一个应用程序,我想根据来自请求的 header 加载不同的配置部分 这是我的一部分 startup.cs public void ConfigureServices(IServiceCollection 服务) { services.AddControllers();
IConfiguration cfg = null;
services.AddScoped<IConfiguration>(x =>
{
cfg = Configuration.GetSection("AppSettings:" + x.GetService<IHttpContextAccessor>()?.HttpContext?.Request?.Headers["xxx"]);
return (cfg);
});
services.AddSingleton<DB.Calendar.Repo>(x => new DB.Calendar.Repo(cfg));
services.AddApplicationInsightsTelemetry();
}
问题是根本没有调用 AddScoped 的 lambda(即使我只是放了一些 console.outs)所以 cfg 保持为空。我做错了什么
传递给 services.AddScoped()
的委托仅在创建新范围时执行(即在 ASP.NET 应用的 HTTP 请求开始时)。这解释了为什么在调用 AddSingleton()
时 cfg
是 null
。
像这样的东西应该可以工作:
services.AddScoped<DB.Calendar.Repo>(x => {
var cfg = Configuration.GetSection("AppSettings:" + x.GetService<IHttpContextAccessor>()?.HttpContext?.Request?.Headers["xxx"]);
return new DB.Calendar.Repo(cfg);
});
一旦你让它工作,明智的做法是将读取正确配置部分的逻辑移动到它自己的服务中,以使其更易于测试(并使其看起来干净)。