❔ Maybe Disposable Object
I want to have a function that returns an HttpClient or an error. The function would take in JSON API user credentials and return an HttpClient with the Base Address and Authorization Headers set if the credentials are valid, otherwise an error message. When consuming this function I was going to use a using statement:
using(var client = MakeNewClient(username, password))
{
}
or...
var clientOrError = MakeNewClient(username, password);
if(client.Error != null)
return;
using(clientOrError.client)
{
}
What should the return type of MakeNewClient() be in order to surface the error and still be able to use it in a using statement? Or is my approach to this wrong all-together?
10 Replies
You could look into a library like OneOf
Then you can make the method return
OneOf<HttpClient, YourErrorType>
and match against itDon't dispose HttpClient
Even though it's disposable, you really do not want to be disposing HttpClient yourself as it can lead to resource issues.
I'm going to have a lot of clients since everyone's credentials will be different, will that cause memory leaks or something?
It can cause socket exhaustion. You want to use IHttpClientFactory instead.
Please read this:
https://josef.codes/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/
Josef Ottosson
You're (probably still) using HttpClient wrong and it is destabiliz...
I try to optimize the fetching and deserialization of data in dotnet core as much as possible. HttpClientFactory and streams are my best friends
Is is better to just create a single static instance and then adjust the authorization header as different people use it?
No, it's better to use IHttpClientFactory as detailed in the article.
ok, I'll give it a read, thanks! 🙂
For that specific case, there is specifically an issue with DNS changes not being respected which can eventually lead to failures.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.