简体   繁体   中英

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.

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() .

Am I doing anything wrong?

app.ApplicationServices does not provide a request-scoped IServiceProvider . It will return a singleton instance of ValueStore when you use GetService<>() . You have two options here:

Use HttpContext.RequestServices :

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

Or inject ValueStore in the Invoke method of a middleware:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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