Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Singleton or Scoped service for making api calls in ASP.NET Core?

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?

like image 831
Navid Rsh Avatar asked Nov 07 '25 11:11

Navid Rsh


1 Answers

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.

like image 136
David Browne - Microsoft Avatar answered Nov 09 '25 23:11

David Browne - Microsoft