I have a .Net Core 3.1 web API, and I have the followings dependencies:
- As Scoped
SomeDbContext(using AddDbContextPool). - As Transient
SomeDbRepository, it recive the aboveSomeDbContext. - As Transient
SomeService, it recive the aboveSomeDbRepository. - As Singleton a factory for
SomeService.
Here the code for injecting the dependencies in Startup.cs
services.AddDbContextPool<SomeDbContext>(options => options.UseSqlServer("connectionsString"));
services.AddTransient<SomeDbRepository>();// recive SomeDbContext
services.AddTransient<SomeService>();// recive SomeDbRepository
//Factory for SomeService
services.AddSingleton<Func<SomeService>>(provider => () =>
{
return provider.GetService<SomeService>();
});
API Controller
//API Controller
public SomeController(Func<SomeService> factory)
{
_someService = factory.Invoke();
}
When I call my API in a multi thread enviroment I get the error:
Error: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext
Why is my DbContext used by different threads? It suposse the Factory returns a new scoped DbContext per request. I use (Invoke) the Factory only one time por request.
If I change the lifetime of the Factory, from Sinlgeton to Scoped, it works ok. But I dont know Why? Why the lifetime of the Factory affects? Could someone explain me why it works that way. Thank a lot guys!!