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?
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.
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. 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With