Search code examples
c#wpfdependency-injectiondotnet-httpclient

IHttpClientFactory and changing the HttpClient


What is the best practice for changing the underlying HttpClient for a IHttpClientFactory

Here is how I create my Dependency Injection:

IServiceCollection serColl = new ServiceCollection();

serColl.AddHttpClient("tester").ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler()
    {
        CookieContainer = Cookies,
    };
});

var serviceProvider = serColl.BuildServiceProvider();

_HTTPClientFactory = serviceProvider.GetService<IHttpClientFactory>();

In this case Cookies holds a number of System.Net.Cookies. My question is if I need to change the cookies how should I do this?


Solution

  • Here how I solved the problem.

    IServiceCollection serColl = new ServiceCollection();
    serColl.AddTransient<CookieHandler>();
    serColl.AddHttpClient("IHTTPRequester");
    serColl.AddHttpClient("HTTPCookieClient").AddHttpMessageHandler<CookieHandler>();
    var serviceProvider = serColl.BuildServiceProvider();
    _HTTPClientFactory = serviceProvider.GetService<IHttpClientFactory>();
    

    Then as HTTPCookieClient has a delegation handler I have the following

    public class CookieHandler : DelegatingHandler
    {
        //Everytime a client call the getasync then this is called and we then add the Cookie header to the call.
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            request.Headers.Add("Cookie", Your Cookie Values go here);
            
            var response = await base.SendAsync(request, cancellationToken);
            return response;
        }
    }