0

I have a use case for HttpMessageHandler that requires new options on instantiation. I believe that IHttpMessageHandlerFactory.CreateHandler is the correct API here, but I'm not sure if this usage is correct:

public class MyDelegatingHandler : DelegatingHandler {
    public MyDelegatingHandler(
        HttpMessageHandler internalHandler
        )
    {
        _internalHandler = internalHandler;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken
        )
    {
        // custom logic
        return await _internalHandler.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }

    private HttpMessageHandler _internalHandler;
}

public class MyHttpClientFactory {
    public MyHttpClientFactory(
        IHttpMessageHandlerFactory factory
        )
    {
        _factory = factory;
    }

    public HttpClient CreateClient(
        // arguments
        )
    {
        return new HttpClient(
            new MyDelegatingHandler(_factory.CreateHandler()),
            disposeHandler: false
            );
    }

    private IHttpMessageHandlerFactory _factory;
}

Assuming MyDelegatingHandler has no state that needs to be disposed on its own, will this correctly use the lifetime management features of HttpClientFactory injected through the IHttpMessageHandlerFactory dependency?

  • I'm not sure, I can see you're not using the factory you inject in the first place. Maybe taking a look at this will help you: https://stackoverflow.com/questions/50747749/how-to-use-httpclienthandler-with-httpclientfactory-in-net-core – Peter Sandor Dec 23 '19 at 16:45
  • thanks; made an edit to clarify the usage of the handler factory and internal handler in my actual code. writing skeleton from scratch is nontrivial – Johnathon Root Dec 23 '19 at 17:13

0 Answers0