public TDbContext GetDbContext() { if (UnitOfWork.EnableObsoleteDbContextCreationWarning && !UnitOfWorkManager.DisableObsoleteDbContextCreationWarning.Value) { Logger.LogWarning( "UnitOfWorkDbContextProvider.GetDbContext is deprecated. Use GetDbContextAsync instead! " + "You are probably using LINQ (LINQ extensions) directly on a repository. In this case, use repository.GetQueryableAsync() method " + "to obtain an IQueryable<T> instance and use LINQ (LINQ extensions) on this object. " ); Logger.LogWarning(Environment.StackTrace.Truncate(2048)); } var unitOfWork = _unitOfWorkManager.Current; if (unitOfWork == null) { throw new AbpException("A DbContext can only be created inside a unit of work!"); } var targetDbContextType = _options.GetReplacedTypeOrSelf(typeof(TDbContext)); var connectionStringName = ConnectionStringNameAttribute.GetConnStringName(targetDbContextType); var connectionString = ResolveConnectionString(connectionStringName); var dbContextKey = $"{targetDbContextType.FullName}_{connectionString}"; var databaseApi = unitOfWork.GetOrAddDatabaseApi( dbContextKey, () => new EfCoreDatabaseApi( CreateDbContext(unitOfWork, connectionStringName, connectionString) )); return((TDbContext)((EfCoreDatabaseApi)databaseApi).DbContext); }
public async Task Should_Replace_DbContext() { _options.GetReplacedTypeOrSelf(typeof(IThirdDbContext)).ShouldBe(typeof(TestAppDbContext)); _options.GetReplacedTypeOrSelf(typeof(IFourthDbContext)).ShouldBe(typeof(TestAppDbContext)); (ServiceProvider.GetRequiredService <IThirdDbContext>() is TestAppDbContext).ShouldBeTrue(); (ServiceProvider.GetRequiredService <IFourthDbContext>() is TestAppDbContext).ShouldBeTrue(); using (var uow = _unitOfWorkManager.Begin()) { var instance1 = await _dummyRepository.GetDbContextAsync(); (instance1 is IThirdDbContext).ShouldBeTrue(); var instance2 = await _dummyRepository.GetDbContextAsync(); (instance2 is TestAppDbContext).ShouldBeTrue(); var instance3 = await _personRepository.GetDbContextAsync(); (instance3 is TestAppDbContext).ShouldBeTrue(); var instance4 = await _fourthDummyRepository.GetDbContextAsync(); (instance4 is IFourthDbContext).ShouldBeTrue(); var instance5 = await _fourthDummyRepository.GetDbContextAsync(); (instance5 is TestAppDbContext).ShouldBeTrue(); // All instances should be the same! instance3.ShouldBe(instance1); instance3.ShouldBe(instance2); instance3.ShouldBe(instance4); instance3.ShouldBe(instance5); await uow.CompleteAsync(); } }