private OsharpDbContextConfig GetDbContextResolveOptionsConfig(Type dbContextType) { IOsharpConfigProvider osharpConfigProvider = _serviceProvider.GetService <IOsharpConfigProvider>(); OsharpConfig osharpConfig = osharpConfigProvider.Create(); OsharpDbContextConfig dbContextConfig = osharpConfig.DbContexts.Values.SingleOrDefault(m => m.DbContextType == dbContextType); if (dbContextConfig == null) { throw new OsharpException($"无法找到数据上下文“{dbContextType}”的配置信息"); } return(dbContextConfig); }
/// <summary> /// 获取指定数据上下文类型<typeparamref name="TEntity"/>的实例 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> /// <typeparam name="TKey">实体主键类型</typeparam> /// <returns><typeparamref name="TEntity"/>所属上下文类的实例</returns> public IDbContext GetDbContext <TEntity, TKey>() where TEntity : IEntity <TKey> where TKey : IEquatable <TKey> { IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>(); Type dbContextType = typeFinder.GetDbContextTypeForEntity(typeof(TEntity)); DbContext dbContext; OsharpDbContextConfig dbContextConfig = GetDbContextResolveOptionsConfig(dbContextType); DbContextResolveOptions resolveOptions = new DbContextResolveOptions(dbContextConfig); IDbContextResolver contextResolver = _serviceProvider.GetService <IDbContextResolver>(); ActiveTransactionInfo transInfo = ActiveTransactionInfos.GetOrDefault(resolveOptions.ConnectionString); //连接字符串的事务不存在,添加起始上下文事务信息 if (transInfo == null) { resolveOptions.ExistingConnection = null; dbContext = contextResolver.Resolve(resolveOptions); IDbContextTransaction transaction = dbContext.Database.BeginTransaction(); transInfo = new ActiveTransactionInfo(transaction, dbContext); ActiveTransactionInfos[resolveOptions.ConnectionString] = transInfo; } else { resolveOptions.ExistingConnection = transInfo.DbContextTransaction.GetDbTransaction().Connection; dbContext = contextResolver.Resolve(resolveOptions); if (dbContext.IsRelationalTransaction()) { dbContext.Database.UseTransaction(transInfo.DbContextTransaction.GetDbTransaction()); } else { dbContext.Database.BeginTransaction(); } transInfo.AttendedDbContexts.Add(dbContext); } return(dbContext as IDbContext); }
/// <summary> /// 初始化一个<see cref="DbContextResolveOptions"/>类型的新实例 /// </summary> public DbContextResolveOptions(OsharpDbContextConfig config) { DbContextType = config.DbContextType; ConnectionString = config.ConnectionString; DatabaseType = config.DatabaseType; }