简体   繁体   English

ASP.NET 5和内置DI容器的每请求范围

[英]Per-request scope with ASP.NET 5 and built-in DI container

I'm investigating the topic of DI in ASP.NET 5, and I faced such a problem - I don't understand how to create a new instance of a service per request. 我正在调查ASP.NET 5中的DI主题,我遇到了这样的问题 - 我不明白如何为每个请求创建一个新的服务实例。

I use the code: 我用的代码是:

services.AddScoped<ValueStore>();

And inside my middlewares I grab the value: 在我的中间件中,我抓住了价值:

var someValueStore = app.ApplicationServices.GetService<ValueStore>();

Full code is available here 完整代码可在此处获得

And my problem is: while I expect this service to be renewed on each request, it doesn't happen, and it behaves as if it was registered as AddSingleton() . 我的问题是:虽然我希望在每个请求上更新此服务,但它不会发生,并且它的行为就像注册为AddSingleton()

Am I doing anything wrong? 我做错了吗?

app.ApplicationServices does not provide a request-scoped IServiceProvider . app.ApplicationServices不提供请求范围的IServiceProvider It will return a singleton instance of ValueStore when you use GetService<>() . 当您使用GetService<>()时,它将返回ValueStore的单例实例。 You have two options here: 你有两个选择:

Use HttpContext.RequestServices : 使用HttpContext.RequestServices

var someValueStore = context.RequestServices.GetService<ValueStore>();

Or inject ValueStore in the Invoke method of a middleware: 或者在中间件的Invoke方法中注入ValueStore

public async Task Invoke(HttpContext httpContext, ValueStore valueStore)
{
    await httpContext.Response.WriteAsync($"Random value = {valueStore.SomeValue}");
    await _next(httpContext);
}

I cloned your repo and this works. 我克隆了你的回购,这很有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM