Base solution for your next web application
Open Closed

Using separate dbcontexts for same DB #10086


User avatar
0
codescientists created
  • What is your product version? 10.0
  • What is your product type (Angular or MVC)? Angular
  • What is product framework type (.net framework or .net core)? Core
  • What is ABP Framework version? ABP 6.0

How can you acquire more than one DbContext instance for the same database? I was expecting to be able to inject multiple repositories into a service and have each use their own DbContext.

The purpose is so that we can run some "parallel" select queries (async/awaiting the SQL response) where concurrency is not a big concern. But this cannot be done if the underlying DbContext is the same instance.

Some simplified code to illustrate: // Repository implementation. Note: IMyRepository includes a GetDbContext() public class MyRepositoryBase<TEntity> : EfCoreRepositoryBase<MyDbContext, TEntity, long>, IMyRepository<TEntity> where TEntity : class, IEntity<long> { public MyRepositoryBase(IDbContextProvider<MyDbContext> dbContextProvider) : base(dbContextProvider) { } } and elsewhere:

// Testing from service var firstRepo = IocManager.Instance.Resolve<IMyRepository>();

var secondRepo = IocManager.Instance.Resolve<IMyRepository>();

bool theseMatch = object.Equals(firstRepo.GetDbContext(), secondRepo.GetDbContext());

// Since DBContext is same instance, cannot await these as they run concurrently... var gotDispatches = firstRepo.GetAllListAsync(); var gotDeliveries = secondRepo.GetAllListAsync(); await Task.WhenAll(gotDispatches, gotDeliveries); ` How can I enforce that the repositories each have their own DbContext, as though they were separate API requests. From looking at ABP source it seems like the IDbContextProvider injected into the repository base is going to always provide the same DbContext for the same unit of work. Is there no way to configure it otherwise?

In terms of dependency injection, I want the DbContexts to be transient just like the service implementations, with one new instance per resolve. Would I need to create a custom IDbContextProvider that just always provided a new DbContext? Is there a better/easier way? What might this break?


1 Answer(s)