DbContextFactory created with Scoped lifetime instead of Singleton
See original GitHub issueI have seen previous issues about DbContextFactory and the suggestion was to use AddTriggeredDbContextFactory
to solve those problems.
However, when we tried to do this it caused a bunch of other issues throughout the codebase because AddTriggeredDbContextFactory seems to cause the context factory to be changed to a scoped lifetime somehow.
We found that using services.AddDbContextFactory<TDbContext>(builder => { ...}, ServiceLifetime.Transient);
solved the issues for us.
I am interested to know if you see any potential issues with using the context factory with a transient service lifetime like this? Our automated tests and passing and some manual tests show that the triggers are working correctly as expected but I worry that there might be some unexpected consequences that will bite us later down the line.
Issue Analytics
- State:
- Created 2 years ago
- Comments:14 (10 by maintainers)
Top GitHub Comments
I opened a very basic PR, I didn’t spend much time on it so please let me know if there are more changes required
This is the current effect of calling
AddTriggeredDbContextPool
,AddTriggeredDbContextFactory
andAddTriggeredPooledDbContextFactory
and this should be fixed.This library needs to grab the current
ServiceProvider
that is used to either get an instance ofIDbContextFactory
or otherwise a Lease on an instance of a DbContext in the pool (each instance essentially acts as a singleton in the latter case). By storing thisServiceProvider
, this library can then associate that ServiceProvider instance with the DbContext so that triggers can resolve services using the same ServiceProvider.There is no need for this custom IDbContextFactory implementation to be registered as Scoped. Instead, Transient will work in both worlds. We should update these registrations to use a Transient registration instead.
Once we update the registrations to
Transient
, we will be able to resolve aIDbContextFactory
from the root ServiceProvider, as this is able to resolve Singleton and Transient services. Any trigger however that relies on a Scoped service will still cause issues as that root ServiceProvider is unable to deal with them. It therefore is strongly recommended to IServiceScope pattern as you highlighted above in singleton services.