Logo

dev-resources.site

for different kinds of informations.

How to use Scoped service from Singleton Service in .Net Core

Published at
12/30/2024
Categories
dotnetcore
dotnet
api
programming
Author
devesh_omar_b599bc4be3ee7
Categories
4 categories in total
dotnetcore
open
dotnet
open
api
open
programming
open
Author
25 person written this
devesh_omar_b599bc4be3ee7
open
How to use Scoped service from Singleton Service in .Net Core

We should be very careful about lifetime of objects in .net core.

Suppose we created Two services one register as Singleton and other as Scoped.

Code

public interface IScopedService
 {  
 }

 public interface ISingletonService
 {

 }

/// Scope service
 public class ScopedService : IScopedService
 {
     public ScopedService()

     {

     }

 }
/// Singelton Service , here we are injecting scope service object
 public class SingletonService : ISingletonService
 {
     public SingletonService(IScopedService svc)

     {

     }

 }
Enter fullscreen mode Exit fullscreen mode

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


builder.Services.AddSingleton<ISingletonService, SingletonService>();

builder.Services.AddScoped<IScopedService, ScopedService>();
Enter fullscreen mode Exit fullscreen mode

Image description

Understanding of code.

we have created two classes Singelton and Scoped and we have injected scoped inside singleton service.

When we run application, we will get below error

Image description

Understanding Error

We have 3 types of service lifetimes:

  1. Singleton — they’re created first time they’re request, and every time after that the same instance will be reused

  2. Scoped — they’re created once per the request (connection)

  3. Transient are created every time you request them from the DI container

_Here we are trying to inject a object that will be created on each user scope request so that required to dispose after each and every request. Here Singelton object will never be going to dispose but scoped object is required to dispose, so this is conflict.
_

As per above explanation we should almost never consume scoped service or transient service from a singleton. You should also avoid consuming transient service from a scoped service.

What is happening when you consume scoped service from a singleton service is known as a captive dependency. It occurs when a service intended to live for a short(er) amount of time gets held by a service that lives for a more extended amount of time. This almost always suggests that you should change something in your design.

*Solution *

If there is need to use Scoped service inside singleton then we need to create scope manually. A new scope can be created by injecting an IServiceScopeFactory into your singleton service. The IServiceScopeFactory has a CreateScope method, which is used for creating new scope instances. IServiceScopeFactory is singelton in itself that’s why it works here.

Please Click here for complete implementation

dotnetcore Article's
30 articles in total
Favicon
.Net tarixi
Favicon
Oh bless me, Father, I have done something unholy: Installing .NET Core on Apple Silicon
Favicon
How to use Scoped service from Singleton Service in .Net Core
Favicon
How to add a Custom fields to Header in .NET Core Web API ?
Favicon
c#(.Net) - Basic Authentication WEB API
Favicon
CRUD operations on Arrays
Favicon
Working with interfaces
Favicon
Iterations
Favicon
Protfolio Website
Favicon
Dependency injection validation error in ASP.NET Core projects
Favicon
.Net Core and Kafka
Favicon
C# Null-Conditional (?.) & Null-Coalescing (??) Operators Explained
Favicon
Change a .Net Console application into an web application
Favicon
Efficient Bulk Operations with UkrGuru.Sql
Favicon
Improve Application Performance using “Fire and Forget” in .NET Core
Favicon
API Versioning in .Net Core.
Favicon
Move objects from one folder to other in the same S3 Bucket using C# in AWS
Favicon
🎉 We Made It: Trending in .NET on Dev.to! 🚀
Favicon
.NET 9 Improvements for ASP.NET Core: Open API, Performance, and Tooling
Favicon
.Net Core Microservice Communication Using Kafka.
Favicon
Getting Started with .NET and Docker Tutorial
Favicon
Experimental attribute in C# is a powerful tool : Let's explore
Favicon
Implementing Chain of Responsibility Pattern in C# : Middleware's Design Pattern
Favicon
How to create a background email sender with outbox pattern integration
Favicon
The End of Microsoft's Monopoly on ASP.NET
Favicon
.NET Core MVC Project Structure : Implementing a Generic Service and Repository Pattern
Favicon
Did you know? How .NET Achieving Language Interoperability (C# + VB.NET = Same Application)
Favicon
These 10+ comparisons cover entire SQL concepts, Is it?
Favicon
NET 9 BinaryFormatter migration paths
Favicon
How to create a background email sender

Featured ones: