Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
kosmakoff Avatar asked Nov 09 '15 15:11

kosmakoff


People also ask

What is difference between Addtransient and Addscoped and Addsingleton?

Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.

What is a .NET dependency DI or IoC container?

IoC Container: also known as Dependency Injection (DI) Container, it is a programming framework that provides you with an automatic Dependency Injection of your components.

What is DI container in ASP.NET Core?

What is DI Container. A DI Container is a framework to create dependencies and inject them automatically when required. It automatically creates objects based on the request and injects them when required. DI Container helps us to manage dependencies within the application in a simple and easy way.


1 Answers

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.

like image 67
Henk Mollema Avatar answered Nov 15 '22 19:11

Henk Mollema