4

I have a class for making API calls. I would like to pass it as dependency and I want to know if it is better to use Singleton or Scoped :

services.AddScoped<IHttpCallService, HttpCallService>();
 or 
services.AddSingleton<IHttpCallService, HttpCallService>();

I know there are differences between Singleton and Scoped in terms of instance creation, but I would like to know which one is more efficient and suitable for this case? And also, if I use Singleton, would it mean that everything would work synchronously?

8
  • 1
    Maybe this will help you understand better : Dependency injection in ASP.NET Core. Commented Apr 12, 2021 at 12:15
  • 1
    What kind of application are you talking about? Commented Apr 12, 2021 at 12:38
  • If you are using an HttpClient... The best approach is use a singleton and make your cals using async/await. HttpClient is designed to work better that way anyways. Commented Apr 12, 2021 at 13:31
  • @AlexeyRumyantsev this is an asp.net core web Api application. Commented Apr 12, 2021 at 16:02
  • 1
    Regarding "would it mean that everything would work synchronously?": In C# there isn't any kind of queue for requests using the same object or method. If multiple threads are all using the same singleton object, each thread has its own stack and is basically independent. The only thing really shared is any fields on the singleton object. Commented Apr 12, 2021 at 16:21

2 Answers 2

7

The recommomended pattern is to have your HttpCallService depend on an HttpClient instance, and then register it as a Typed Client with

services.AddHttpClient<HttpCallService>();

This will register HttpCallService as a transient service.

Sign up to request clarification or add additional context in comments.

Comments

0

Best recommendation is to use singleton in this scenario when your dealing with with api calls. Below article explains what is the issue you don't use HttpClient as singleton

services.AddSingleton<IHttpCallService, HttpCallService>();

Read this article for more in depth knowledge on this https://www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.