kos*_*off 7 c# asp.net asp.net-core
我正在调查ASP.NET 5中的DI主题,我遇到了这样的问题 - 我不明白如何为每个请求创建一个新的服务实例.
我用的代码是:
services.AddScoped<ValueStore>();
Run Code Online (Sandbox Code Playgroud)
在我的中间件中,我抓住了价值:
var someValueStore = app.ApplicationServices.GetService<ValueStore>();
Run Code Online (Sandbox Code Playgroud)
完整代码可在此处获得
我的问题是:虽然我希望在每个请求上更新此服务,但它不会发生,并且它的行为就像它被注册为AddSingleton().
我做错了吗?
Hen*_*ema 10
app.ApplicationServices不提供请求范围IServiceProvider.它会ValueStore在你使用时返回一个单例实例GetService<>().你有两个选择:
用途HttpContext.RequestServices:
var someValueStore = context.RequestServices.GetService<ValueStore>();
Run Code Online (Sandbox Code Playgroud)
或者注入中间件ValueStore的Invoke方法:
public async Task Invoke(HttpContext httpContext, ValueStore valueStore)
{
await httpContext.Response.WriteAsync($"Random value = {valueStore.SomeValue}");
await _next(httpContext);
}
Run Code Online (Sandbox Code Playgroud)
我克隆了你的回购,这很有效.
| 归档时间: |
|
| 查看次数: |
841 次 |
| 最近记录: |