Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Andrei 15 posts 99 karma points
    Aug 25, 2021 @ 10:57
    Andrei
    0

    How to register IHttpClientFactory to use HttpClient correctly with multiple configurations

    In the example from Microsoft docs, they register the HttpClient factory with the specific extension method like:

    services.AddHttpClient<IMyCustomService, CustomService>(httpClient =>
    {
        httpClient.BaseAddress = new Uri(Configuration["BaseUrl"]);
    })
    

    Umbraco is registering services with composers and I can't find any way to hook into an IServiceCollection where I could use the extension method.

    Any idea how I can achieve the same thing as above with the 'umbraco way'?

  • Lucas Michaelsen 32 posts 233 karma points
    Sep 16, 2021 @ 11:27
    Lucas Michaelsen
    0

    Hello Andrei.

    The example from microsoft is for .NET Core.

    The way I normal do this HttpClient in terms of Umbraco and .Net 4.x. I start by creating a Service of Depency injectable Class. Where HttpClient is Static, without dispose it. It means i share the connectionPool the HttpClient start.

    public class TestService : ITestService {
         private static HttpClient _httpClient;
    
         public TestService() {
              if (_httpClient == null) {
                   _httpClient = new HttpClient() { 
                       BaseAddress = new Uri("https://google.com") 
                   }
              }
         }
    
         public bool CallGoogle() {
             return _httpClient.GetAsync("")
                 .GetAwaiter()
                 .GetResult()
                 .IsSuccessStatusCode;
         }
    }
    

    From my RenderMvcController it will be like this:

     public class FrontpageController : RenderMvcController {
          private readonly ITestService _testService;
    
          public FrontpageController(ITestService testService) {
               _testService = testService;
          }
    
          public override ActionResult Index(ContentModel contentModel) {
               _testService.CallGoogle();
    
               return CurrentTemplate(contentModel);
          }
     }
    

    At last but not least, i register the component to Umbraco DI, with a lifetime deffindt to be a singleton Lifetime.Singleton - one unique instance for the whole web application: The single instance will be shared across all web requests.

    public class IocComposer : IUserComposer {
         public void Compose(Composition composition) {
              composition.Register<ITestService, TestService(liftetime: Lifetime.Singleton);
         }
    }
    

    Hops this will help you :)

Please Sign in or register to post replies

Write your reply to:

Draft