Jawahar
Jawahar

Reputation: 233

cannot consume a scoped service from singleton

I am getting the above error and I realize why, but the odd behavior I see that it only happens in our Dev environment and not in for example our staging or Production environment and it is the exact same code. In the startup there is :

services.AddSingleton<ExcahngeService>();
services.AddScoped<ITradingService, TradingService>();

This throws the error: "cannot consume a scoped service from singleton"

Could this be due to a timing issue, where the environment is slower ?

Upvotes: 3

Views: 7285

Answers (2)

Ali Sadri
Ali Sadri

Reputation: 1686

As Microsoft best practice you should create new scope and get scoped service from ServiceProvider https://learn.microsoft.com/en-us/dotnet/core/extensions/scoped-service

Upvotes: -1

Kazi Rahiv
Kazi Rahiv

Reputation: 681

Scoped instance lifetime is limited, It is only available per request. So you are consuming an instance from Scoped service into Singleton and the error throws because of the scoped service is disposed. Either make both Singleton or Scoped

Upvotes: 2

Related Questions