Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ApplicationServices and RequestServices in Microsoft.AspNet.Http.HttpContext?

Tags:

asp.net-core

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.

like image 504
Ricky Avatar asked Nov 25 '14 09:11

Ricky


1 Answers

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.

like image 185
Hao Kung Avatar answered Dec 12 '22 09:12

Hao Kung