Why singleton hates scoped injection in .NET dependency injection

Опубликовано: 28 Январь 2025
на канале: Round The Code
1,742
49

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 📖
https://www.roundthecode.com/dotnet-c...

► More information:
https://www.roundthecode.com/dotnet-b...

► 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