C
C#10mo ago
Dyad

❔ 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
mg
mg10mo ago
You could look into a library like OneOf Then you can make the method return OneOf<HttpClient, YourErrorType> and match against it
mtreit
mtreit10mo ago
Don'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.
Dyad
Dyad10mo ago
I'm going to have a lot of clients since everyone's credentials will be different, will that cause memory leaks or something?
mtreit
mtreit10mo ago
It can cause socket exhaustion. You want to use IHttpClientFactory instead.
mtreit
mtreit10mo ago
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
Dyad
Dyad10mo ago
Is is better to just create a single static instance and then adjust the authorization header as different people use it?
mtreit
mtreit10mo ago
No, it's better to use IHttpClientFactory as detailed in the article.
Dyad
Dyad10mo ago
ok, I'll give it a read, thanks! 🙂
mtreit
mtreit10mo ago
For that specific case, there is specifically an issue with DNS changes not being respected which can eventually lead to failures.
Accord
Accord10mo ago
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.
Want results from more Discord servers?
Add your server
More Posts