private void SetDefaultDbContext <TContext>(DbContextSettingsBuilder builder) where TContext : DbContext, INewDatabaseFlag { if (builder.IsDefaultDbContext) { if (DefaultDbContext == null) { this.DefaultDbContext = typeof(TContext); this.DefaultDbConnectionName = builder.ConnectionName; } else { throw new ArgumentException($"已指定了默认的 DbContext 类型 '{this.DefaultDbContext.FullName}', 不能指定多个默认的DbContext。"); } } }
private DbBuilder AddDbContext <TContext>(String dbConnectionName, String connectionString, Action <DbContextSettingsBuilder> setup) where TContext : DbContext, INewDatabaseFlag { if (dbConnectionName.IsNullOrWhiteSpace() && connectionString.IsNullOrWhiteSpace()) { throw new ArgumentException($"必须提供非空的 {nameof(dbConnectionName)} 或 {nameof(connectionString)}。"); } String connName = dbConnectionName; if (connName.IsNullOrWhiteSpace()) { connName = Guid.NewGuid().ToString(); this.Setup += ((DbOptions innerOptions) => { innerOptions.ConnectionStrings.Add(connName, connectionString); }); } this.DbContexts[connName] = typeof(TContext); DbContextSettingsBuilder builder = new DbContextSettingsBuilder(connName, connectionString); setup?.Invoke(builder); SetDefaultDbContext <TContext>(builder); DbContextSettings settings = builder.Build(); this.DbSettings[typeof(TContext)] = settings; if (!this.DbConfigurings.ContainsKey(settings.DbProvider.GetType())) { this.DbConfigurings[settings.DbProvider.GetType()] = services => settings.DbProvider.OnAddDependencies(services); } this.DbConfigurings[typeof(TContext)] = c => { var configure = new Action <IServiceProvider, DbContextOptionsBuilder>((sp, b) => { var options = sp.GetRequiredService <IOptions <DbOptions> >(); settings.DbProvider.OnBuildContext(typeof(TContext), b, options.Value); b.UseLoggerFactory(sp.GetRequiredService <ILoggerFactory>()); b.Options.WithExtension <IDbContextOptionsExtension>(new DbSettingsrExtension(settings)); b.ReplaceService <IModelCustomizer, SchubertModelCustomizer>(); }); if (settings.UsePool) { c.AddDbContextPool <TContext>(configure, settings.PoolSize); } else { c.AddDbContext <TContext>(optionsAction: configure); } }; if (builder.IsDefaultDbContext) { this.DbConfigurings[typeof(TContext)] += services => { services.AddScoped(typeof(DbContext), s => (DbContext)s.GetRequiredService(typeof(TContext))); }; } return(this); }