SlackLogger icon indicating copy to clipboard operation
SlackLogger copied to clipboard

Consider IHttpClientFactory instead of static HttpClient

Open dahlbyk opened this issue 3 years ago • 4 comments

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests

https://www.nuget.org/packages/Microsoft.Extensions.Http

dahlbyk avatar Jul 13 '21 04:07 dahlbyk

How to support applications that don't use IHttpClientFactory? Would we have to attempt to resolve it, but default to a static one when we are unable to?

severisv avatar Jul 14 '21 13:07 severisv

How to support applications that don't use IHttpClientFactory? Would we have to attempt to resolve it, but default to a static one when we are unable to?

I think AddHttpClient() is designed to be able to support something like this:

    public static class SlackConfiguration
    {
        public static ILoggingBuilder AddSlack(this ILoggingBuilder builder)
        {
            builder.Services.AddHttpClient(nameof(SlackLogger));
            builder.Services.AddTransient<ILoggerProvider, LoggerProvider>();

            return builder;
        }
    }

    internal class SlackService
    {
        private async Task PostAsync(/* ... */)
        {
            // ...
            var httpClient = _httpClientFactory.CreateClient(nameof(SlackLogger));
            await httpClient.PostAsync(url, content).ConfigureAwait(false);
        }
    }

Or SlackService could be refactored as a transient typed client that would be directly injected into SlackLogger.Logger instead of newed up.

Glad to take a shot at an implementation. The project I'm currently using this on doesn't use IHttpClientFactory.

dahlbyk avatar Jul 14 '21 16:07 dahlbyk

Allright, that sounds good ☺

severisv avatar Jul 15 '21 09:07 severisv

I do still plan to get back to this. Someday.™

dahlbyk avatar Apr 20 '22 01:04 dahlbyk