Asp.net 核心 2.0 中间件 - 使用运行时更改的 appsettings 中的参数
Asp.net core 2.0 middleware - Use parameters from appsettings which changes on runtime
我们需要根据 appsettings.json 中的参数在中间件中做一些工作。参数可以在运行时更改。
为此,我可以在设置文件注册时设置 reloadOnChange
builder.AddJsonFile("appsettings.json",
可选:false,reloadOnChange:true)
这适用于我在控制器内使用 IOptionsSnapshopt 的情况,因为控制器是根据请求创建的。但是一个中间件是perlifetime.
我发现 哪里写了如何从 appsettings 访问参数。 --> 但如果参数在运行时发生变化,这将不起作用。
根据文档ASP.NET Core Middleware: Per-request dependencies
Because middleware is constructed at app startup, not per-request, scoped lifetime services used by middleware constructors are not shared with other dependency-injected types during each request. If you must share a scoped service between your middleware and other types, add these services to the Invoke
method's signature. The Invoke
method can accept additional parameters that are populated by dependency injection.
例如,不是在构造函数中,而是将 IOptionsSnapshot
参数添加到 Invoke
方法。
public static class HelloWorldMiddlewareExtensions
{
public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HelloWorldMiddleware>();
}
}
public class HelloWorldMiddleware
{
private readonly RequestDelegate _next;
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IOptionsSnapshopt<AppSettings> options)
{
await context.Response.WriteAsync($"PropA: {options.Value.PropA}");
}
}
public class AppSettings
{
public string PropA { get; set; }
}
我们需要根据 appsettings.json 中的参数在中间件中做一些工作。参数可以在运行时更改。
为此,我可以在设置文件注册时设置 reloadOnChange builder.AddJsonFile("appsettings.json", 可选:false,reloadOnChange:true)
这适用于我在控制器内使用 IOptionsSnapshopt 的情况,因为控制器是根据请求创建的。但是一个中间件是perlifetime.
我发现
根据文档ASP.NET Core Middleware: Per-request dependencies
Because middleware is constructed at app startup, not per-request, scoped lifetime services used by middleware constructors are not shared with other dependency-injected types during each request. If you must share a scoped service between your middleware and other types, add these services to the
Invoke
method's signature. TheInvoke
method can accept additional parameters that are populated by dependency injection.
例如,不是在构造函数中,而是将 IOptionsSnapshot
参数添加到 Invoke
方法。
public static class HelloWorldMiddlewareExtensions
{
public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HelloWorldMiddleware>();
}
}
public class HelloWorldMiddleware
{
private readonly RequestDelegate _next;
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IOptionsSnapshopt<AppSettings> options)
{
await context.Response.WriteAsync($"PropA: {options.Value.PropA}");
}
}
public class AppSettings
{
public string PropA { get; set; }
}