2

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

jps
  • 20,041
  • 15
  • 75
  • 79
Muhammad Junaid
  • 129
  • 1
  • 5
  • Does this answer your question? [Cannot consume scoped service 'MyDbContext' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'](https://stackoverflow.com/questions/51618406/cannot-consume-scoped-service-mydbcontext-from-singleton-microsoft-aspnetcore) – Jeremy Lakeman Jul 28 '21 at 04:02

1 Answers1

2

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
    }
}
sa-es-ir
  • 3,722
  • 2
  • 13
  • 31