/// <summary> /// 获取指定类型的数据上下文对象 /// </summary> /// <param name="resolveOptions">上下文解析选项</param> /// <returns></returns> public IDbContext Resolve(DbContextResolveOptions resolveOptions) { Type dbContextType = resolveOptions.DbContextType; IDbContextOptionsBuilderCreator builderCreator = _serviceProvider.GetServices <IDbContextOptionsBuilderCreator>() .FirstOrDefault(m => m.Type == resolveOptions.DatabaseType); if (builderCreator == null) { throw new OsharpException($"无法解析类型为“{resolveOptions.DatabaseType}”的 {typeof(IDbContextOptionsBuilderCreator).FullName} 实例"); } DbContextOptionsBuilder optionsBuilder = builderCreator.Create(resolveOptions.ConnectionString, resolveOptions.ExistingConnection); DbContextModelCache modelCache = _serviceProvider.GetService <DbContextModelCache>(); IModel model = modelCache.Get(dbContextType); if (model != null) { optionsBuilder.UseModel(model); } DbContextOptions options = optionsBuilder.Options; //创建上下文实例 if (!(ActivatorUtilities.CreateInstance(_serviceProvider, dbContextType, options) is DbContext context)) { throw new OsharpException($"实例化数据上下文“{dbContextType.AssemblyQualifiedName}”失败"); } return(context as IDbContext); }
/// <summary> /// 获取指定类型的数据上下文对象 /// </summary> /// <param name="resolveOptions">上下文解析选项</param> /// <returns></returns> public DbContext Resolve(DbContextResolveOptions resolveOptions) { Type dbContextType = resolveOptions.DbContextType; IDbContextOptionsBuilderCreator builderCreator = _serviceProvider.GetServices <IDbContextOptionsBuilderCreator>() .FirstOrDefault(m => m.Type == resolveOptions.DatabaseType); if (builderCreator == null) { throw new OsharpException($"无法解析类型为“{resolveOptions.DatabaseType}”的 {typeof(IDbContextOptionsBuilderCreator).FullName} 实例"); } DbContextOptions options = builderCreator.Create(resolveOptions.ConnectionString, resolveOptions.ExistingConnection).Options; DbContext context = ActivatorUtilities.CreateInstance(_serviceProvider, dbContextType, options) as DbContext; if (context == null) { throw new OsharpException($"实例化数据上下文“{dbContextType.AssemblyQualifiedName}”失败"); } return(context); }