I'm wondering if my implementation in my webAPI is correct:
Startup.cs => ConfigureServices
services.AddHttpClient("MyHttpClient")
Startup.cs => Configure
applicationLifetime.ApplicationStopping.Register(() => {
MyController.httpClient.Dispose();
});
Controller
private static IHttpClientFactory _httpClientFactory;
public static HttpClient httpClient = null;
public MyController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
if (httpClient == null)
{
httpClient = _httpClientFactory.CreateClient("MyHttpClient");
}
}
Methods
[HttpGet]
[Consumes("application/x-www-form-urlencoded")]
public async void MyMethod1() {
await httpClient.SendAsync()
....
}
[HttpGet]
[Consumes("application/x-www-form-urlencoded")]
public async void MyMethod2() {
await httpClient.SendAsync()
....
}
Well, based on your shared code snippet apparently seems that implementations would work. However, you can improve it in few areas. For instance, you have made
IHttpClientFactoryasprivate staticbut the recommended practice is, it should beprivate readonly, I'm not sure, why have you decorate with static, do you want the value of this variable would be changed only in the static constructor or not.Another important point is that, async call should be deal with Task and
async Taskis the natural approach because, if you useasync voidwhich has critical disadvantages and can restricted to your event handler also block your request pool. This is why async void is never encourage to use. You can get more details here.Finally, I found one more inconsistency but its minor, however, I am little scrupulous here in this line, if you define
HttpClient httpClient = nullthat means, you want this as nullable, so this should be as following:So I left
HttpClient?as nullable, thus thenullassignment wouldn't yell at me.Therefore, I think, your whole implementation can be improved as following:
Apart from above implementation, I would like to inform, depending on the requirement there are several ways for
IHttpClientFactoryyou could consier.For example, CreateClient and Typedclients of IHttpClientFactory
Note: Please refer to this official document, if you want to know more details about other consumption pattern.