Why singleton hates scoped injection in .NET dependency injection

preview_player
Показать описание
Singleton, scoped and transient are the service lifetimes available when using dependency injection in .NET.

Most services can inject other services regardless of their lifetime. However, if you attempt to inject a scoped service into a singleton, you get a "Cannot consumed scoped service" error.

This can cause a problem if you're using Entity Framework for a database query in a service with a singleton lifetime, like a background service or SignalR.

We'll have a look at why this is and how we can use the IServiceProvider instance to create a custom scope so that we are able to use services that have a scoped lifetime.

📖 Learn .NET and C# with our online courses 📖

► More information:

► Chapters
0:00 Overview of the problem
0:24 Learn dependency injection with our online course
0:34 Service injection
1:44 Why can't a singleton inject a scoped?
2:14 When is this a problem?
2:50 Demo on the problem and how to resolve
5:18 Learn dependency injection with our online course
Рекомендации по теме
Комментарии
Автор

1:28 DI cannot inject a scoped service A into a singleton B because there could be a several instances of scoped service A in other scopes, correct?
Then, from what scope will a transient service be resolved when injecting it into a singleton? Is it a root scope? Is there some documentation or source code that clarifies that?

suavespade
Автор

insert "You Did It. The Crazy Son of a Bitch, You Did It" meme, i was trying to solve this issue for a couple hours thanks broh greatings from Chile

vladimirEncina