Reputation: 1233
May I know what is wrong with following line of code:-
Why I can't use singleton on it?
services.AddSingleton<IProductRepository, ProductRepository>();
I have been getting 500 internal server error on the above code, however it is working fine with Transient
and Scoped
.
Upvotes: 2
Views: 5873
Reputation: 32139
According to Microsoft Documentiaon:
It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.
Now look at the following code of your ConfigureServices
method in Startup
class:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
There is a second parameter in the UseSqlServer
method for Service Lifetime whose default value is
ServiceLifetime.Scoped
. May be you didn't specify the second parameter so it is taking the default value ServiceLifetime.Scoped
. That means your DbContext
has been registered as Scoped service
. Now if you use your DbContext
in ProductRepository
then your ProductRepository
has to be resisted as Scoped Service
too otherwise ASP.NET Core DI provider cannot resolve it.
Now If you really want to register your ProductRepository
as Singleton
Service then make your DbContext
also Singleton
as follows:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),ServiceLifetime.Singleton);
Now it should work!
Note: I assumed that your ProductRepository
is dependent on DbContext
. If not then your ProductRepository
repository must be dependent on a service which is registered as a Scoped
Service and that's why currently you are not able to use ProductRepository
as Singleton
.
Upvotes: 1
Reputation: 247571
I assume based on the provided pattern that the repository depends on a DbContext
?
public class ProductRepository : IProductRepository {
public ProductRepository (MyDbContext db) {
//...
}
}
Which tends to be registered as scoped.
If you try to register a singleton with scoped dependencies, it may cause the service to have incorrect state when processing subsequent requests.
Reference Dependency injection in ASP.NET Core : Service Lifetimes
Upvotes: 3