Replies: 1 comment 5 replies
-
The scope service check only happens in development, originally it was done that way to save on performance at runtime and avoid breaking changes but maybe its time to always do scope validation by default. There is no scope when you inject into a background thread, its a singleton so the "scope" is top level. See https://ankitvijay.net/2020/03/17/net-core-and-di-beware-of-captive-dependency/ |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
There is a strange behavior in my project.
When I inject a scoped service into my BackgroundService there is no exception be threw when BackgroundService be activated if I am not use development environment.
I can access the scoped service and call it's methods. The BackgroundService also works fine. Everything is fine.
But if I switch back to development environment then run the same code that will throw an exception as expected:
Cannot consume scoped service 'DevelopmentTest.IMyService' from singleton
This is correct behavior as my experience. All my experience and all the docmentations said:
BackgroundService
will be registered as singleton and in singleton service you can not inject a scoped service directly otherwise theBackgroundService
will run failed.docmentations in micorsoft learn:
consuming-a-scoped-service-in-a-background-task
Use scoped services within a BackgroundService
So Am I wrong?
Anybody can explain me more? It confuses me a lot.
Thanks.
Sample:
.NET SDKs installed:
8.0.400 [C:\Program Files\dotnet\sdk]
.NET runtimes installed:
Microsoft.AspNetCore.App 8.0.8 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 8.0.8 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 8.0.8 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Example in Github here: DevelopmentTest
Beta Was this translation helpful? Give feedback.
All reactions