Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddHttpContextAccessor in ConfigureServices vs per HttpClient

Is there any difference between adding the httpContextAccessor one time in ConfigureServices method versus adding the HttpContextAccessor per HttpClient configured.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // FIRST VERSION
    services.AddHttpContextAccessor();

    // SECOND VERSION
    var myService1 = services.AddHttpClient<TestHttpClient1>(c =>
    {
        c.BaseAddress = new Uri(Configuration["TestHttpClient1"]);
    });
    myService1.Services.AddHttpContextAccessor();

    var myService2 = services.AddHttpClient<TestHttpClient2>(c =>
    {
        c.BaseAddress = new Uri(Configuration["TestHttpClient2"]);
    });
    myService2.Services.AddHttpContextAccessor();
}

My guess would be to think that in the second version, we have two singleton, one will be used for class TestHttpClient1 and the other one for TestHttpClient2 but I dont see why we do that because I saw this code in production.

like image 830
John Avatar asked May 17 '26 13:05

John


1 Answers

Is there any difference between adding the httpContextAccessor one time in ConfigureServices method versus adding the HttpContextAccessor per HttpClient configured.

No, there's no difference whatsoever. myService1.Services and myService2.Services both reference the same IServiceCollection as the services variable. The first call (services.AddHttpContextAccessor()) will register the service, but the next two calls (myService1.Services.AddHttpContextAccessor() and myService2.Services.AddHttpContextAccessor()) will no-op (do nothing).

To put that all in to context, here's an extract from the source code for AddHttpClient<TClient>(...) (source):

var builder = new DefaultHttpClientBuilder(services, name);
// ...
return builder;

A new instance of DefaultHttpClientBuilder is created, which wraps up the IServiceCollection that's passed in. As this is an extension method, services here refers to the same services as in your ConfigureServices method. This is then exposed through IHttpClientBuilder.Services, which is what you're using when you reference e.g. myService1.Services.

The call to AddHttpContextAccessor uses TryAddSingleton, which will register the service only if it hasn't already been registered (source):

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In your example, it has already been registered by that first call to services.AddHttpContextAccessor(), which means the next two registration attempts do nothing.

like image 127
Kirk Larkin Avatar answered May 19 '26 01:05

Kirk Larkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!