1

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 ?

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
Jawahar
  • 183
  • 4
  • 16
  • You can refer to the [link](https://stackoverflow.com/questions/38138100/addtransient-addscoped-and-addsingleton-services-differences) and learn more about the lifetime of scoped and singleton. – Yiyi You Sep 06 '22 at 07:18
  • The reason you are only seeing this error in your developer environment, is because Microsoft decided (probably because of performance concerns) to only check for these types of issues while the application is running in dev mode. For more info, read [this](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scope-validation). – Steven Sep 06 '22 at 09:34
  • Thanks @Steven We will need to correct our code nevertheless to allow us to have a working solution in Development. – Jawahar Sep 06 '22 at 14:56
  • Even if you see the error in the development environment, the error exists, because injecting scoped instances in singletons is most likely a bug. Even if you don't see the exception in production, your program is most likely broken anyway. It's very important to fix the issue. – Steven Sep 07 '22 at 08:51
  • @Steven this section might be more relevant as it specifically says "By default, in the development environment, resolving a service from another service with a longer lifetime throws an exception" - https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scoped – David Klempfner May 12 '23 at 02:19

2 Answers2

1

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

Kazi Rahiv
  • 529
  • 3
  • 6
0

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

Ali Sadri
  • 1,570
  • 14
  • 15