Below is a very common exception in .net core, and we get this exception when we use the scope service inside the singleton service.
We should be very careful about the lifetime of objects in the .net core.
Suppose we created Two services, one registered as Singleton and the other as Scoped. Consider the below code.
public interface IScopedService
{
}
public interface ISingletonService
{
}
/// Scoped service
public class ScopedService : IScopedService
{
public ScopedService()
{
}
}
/// Singleton Service, here we are injecting scoped service object
public class SingletonService : ISingletonService
{
private readonly IScopedService _scopedService;
public SingletonService(IScopedService svc)
{
_scopedService = svc;
}
}
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>();

Understanding of code.
We have created two classes, Singelton and Scoped, and we have injected scope into the singleton service.
When we run the application, we will get the below error.

Understanding Error
We have three types of service lifetimes.
- Singleton: they’re created the first time they’re requesting, and every time after that, the same instance will be reused
- Scoped: they’re created once per the request (connection)
Transients are created every time you request them from the DI container
Here, we are trying to inject an object that will be created on each user scope request so that it is required to be disposed of after each and every request. Here, the Singelton object will never be disposed of, but the scoped object is required to be disposed of, so this is a conflict.
As per the 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.




Join the conversation! Your thoughts help the community grow.