0

I'm upgrading to version 107 restsharp and i'm wondering if both these options below are ok ways of doing dependency injection in dotnet with restsharp.

The documents say don't create a new restsharp for every request (connection pool exhaustion resaons) but if the httpclient is injected via the constructor will I be get the benefit of DNS resolution changes even though rest client is contained in transient scoped object (i think that's what AddHttpClient will do). I know there will be some price to pay for creating a transient object, but for a general purpose business app maybe that's fine?

Recommended way as described in the documentation

services.AddSingleton<IMyClient, MyClient>();

public class MyClient : IMyClient
{
    protected readonly RestClient _restClient;

    public MyClient()
    {
        _restClient = new RestClient();
    }
}

OR: is it ok to do this?

services.AddHttpClient<IMyClient, MyClient>();

public class MyClient : IMyClient
{
    protected readonly RestClient _restClient;

    public MyClient(HttpClient httpClient)
    {
        _restClient = new RestClient(httpClient);
    }
}
Paul McTigue
  • 221
  • 2
  • 7
  • Hi, so what's wrong with your code now? Did you have got any error? – Rena Jun 24 '22 at 08:54
  • Both options work. But the docs recommend creating a client as a singleton and new-ing up a restclient internally - as in the first option above. Option 2 uses AddHttpClient and that will new-up a RestClient everytime as it'll be a transient but is it ok because it's passing in the httpclient? Also by passing in the httpclient I assume I'll get the benefit of DNS resolution. And injecting httpclient makes testing possible because I can setup with httpmessagehandler. Although I can do this by passing restclient in the singleton's constructor. Just wondered if there's any pitfalls in option 2 – Paul McTigue Jun 24 '22 at 14:16

1 Answers1

0

You should AddSingleton, not AddHttpClient as per official documentation:

https://restsharp.dev/v107/#restclient-lifecycle

If you use a dependency-injection container, register your API client as a singleton.

I believe it's becouse RestClient is managing the connection pools and addressing known issues, that AddHttpClient would typically address.

If you would use HttpClient directly, you should follow Microsofts recommendations from below URL, where you have a choice of Singleton or AddHttpClient: https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use

Also, not sure how your 2nd option works at this point.

Also, great video explaining more about what AddHttpClient does (sets HttpClient as Transient etc):

https://www.youtube.com/watch?v=Z6Y2adsMnAA&t=335s

Edgaras
  • 449
  • 3
  • 14