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);
}
}
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:
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'?
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.
From my RenderMvcController it will be like this:
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.
Hops this will help you :)
is working on a reply...