In Startup
class, I can add services in ConfigureServices
method. When I want to get a certain service, there are 2 properties in HttpContext instance, ApplicationServices
and RequestServices
. I wonder the difference between them and how to use them properly.
Edit #1: For example, in Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICache, InProcessCache>(); // Line 1
services.AddSingleton<ISystemClientResolver>(SystemClientResolver.CreateInstance); // Line 2
services.AddScoped<SystemClient>(); // Line 3
services.AddRvcBusiness(); // Line 4
services.AddMvc(); // Line 5
}
If I don't call app.UseRequestServices()
in Configure(IApplicationBuilder app)
method, I can get SystemClient
instance by Context.ApplicationServices.GetService(typeof(SystemClient))
, but it's not per-request basis, it seems singleton and Context.RequestServices
is null. Once I call app.UseRequestServices()
like this:
public void Configure(IApplicationBuilder app)
{
app.UseRequestServices();
// ...
}
Context.RequestServices
is not null and I can get SystemClient
instance by Context.RequestServices.GetService(typeof(SystemClient))
and the instance is per-request basis.
ApplicationServices
are for the lifetime of your app, while RequestServices
are scoped to a particular request (HttpContext
). Furthermore, RequestServices
can be null. A special RequestContainer middleware is what initializes RequestServices
:
app.UseRequestServices()
will use the result of ConfigureServices
as RequestServices
app.UseServices()
and its overloads let you specify/modify the request services
Also if you use routing/or any security auth middleware, they will automatically ensure RequestServices are populated as well, since they rely on request scoped services themselves.
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