kosmakoff
kosmakoff

Reputation: 368

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?

Upvotes: 9

Views: 2461

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46591

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.

Upvotes: 12

Related Questions