How to utilize Scoped Service inside Singleton Service

Viewed 127

I have a service name e.g. "Service1.cs" I have registered it as singleton, I have another Service "Service2.cs" and it is registered as Scoped. I want to inject "service2" into "Service1" But As we can't that its giving error, is there any way to consume scoped service into singleton service

1 Answers

As you know when use a scoped service in singleton service, that instance of scoped service behave like a singleton and alive in application and cause to memory leak. I think a good way is to use IServiceScopeFactory and get your scoped service and use it and dispose it like this:

public class SingletonService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public SingletonService(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public Task SampleMethod()
    {
        using var scope = _scopeFactory.CreateScope();

        var scopedService = scope.ServiceProvider.GetRequiredService<IScopedService>();

        //use scope service
        //finally service will disposed because of using statement
    }
}
Related