Home > Mobile >  Call IServiceScopeFactory.CreateScope() in a scoped service
Call IServiceScopeFactory.CreateScope() in a scoped service

Time:01-29

What happens if I call IServiceScopeFactory.CreateScope() from a service which was already added as a scoped using services.AddScoped? Does it create a new scope and then a new instance of each requested scoped service when I call scope.ServiceProvider.GetRequiredService?

The backstory:

I have got a legacy project from from another developer, and now I am trying to identify and resolve several bugs. First of all, I have something what looks like a database connection leak when using Entity Framework. I see this error under high load:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

The thing is that, there are some scoped services which create a new scope and request a DatabaseContext, which is scoped by default in EF.

CodePudding user response:

IServiceScopeFactory.CreateScope will create a new scope, entirely independent of any current scope. If you resolve a scoped service from the new scope, it will return a new instance of that service.

When you Dispose of that scope, all IDisposable services created by that scope should be resolved. If you're leaking scoped service instances, then it's worth checking that every IServiceScope created is also disposed of.

  •  Tags:  
  • Related