Query request scope with ASP.NET 5 and built-in DI container

I am learning a DI topic in ASP.NET 5, and I came across such a problem - I do not understand how to create a new instance of the service for each request.

I am using the code:

services.AddScoped<ValueStore>(); 

And inside my intermediaries, I take the meaning:

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

Full code is available here.

And my problem is that although I expect this service to be updated on every request, it will not happen, and it behaves as if it were registered as AddSingleton() .

Am I doing something wrong?

+6
source share
1 answer

app.ApplicationServices does not provide an IServiceProvider with the request. It will return one instance of ValueStore when using GetService<>() . You have two options:

Use HttpContext.RequestServices :

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

Or enter ValueStore in the middleware Invoke method:

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

I cloned your repo and it works.

+8
source

All Articles