/// <summary> /// 开始初始化数据库 /// </summary> /// <param name="config">数据库配置信息</param> public virtual void Initialize(DataConfig config) { //没有上下文,添加默认上下文 if (config == null || !config.ContextConfigs.Any()) { DbContextConfig contextConfig = GetDefaultDbContextConfig(); if (config == null) { config = new DataConfig(); config.ContextConfigs.Add(contextConfig); } else { config.ContextConfigs.Add(contextConfig); } } //如果业务上下文存在开启数据日志功能,并且日志上下文没有设置,则添加日志上下文 //helang //if (config.ContextConfigs.All(m => m.ContextType != typeof(LoggingDbContext))) //{ // DbContextConfig contextConfig = GetLoggingDbContextConfig(); // config.ContextConfigs.Add(contextConfig); //} foreach (DbContextConfig contextConfig in config.ContextConfigs) { DbContextInit(contextConfig); } }
/// <summary> /// Use EntityFramework Core with PostgreSql /// </summary> /// <param name="context"></param> /// <param name="optAct"></param> /// <typeparam name="TContext"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IDbContextConfig UseEfCoreWithPostgreSql <TContext>( this DbContextConfig context, Action <EfCoreOptions> optAct = null) where TContext : DbContext, IEfContext { if (context is null) { throw new ArgumentNullException(nameof(context)); } var opt = EfCoreOptionsHelper.CreateOptions(optAct); EfCoreOptionsHelper.GuardOptions(opt); context.RegisterDbContext(services => { if (!string.IsNullOrWhiteSpace(opt.ConnectionString)) { EfCoreOptionsRegistrar.Register <TContext>(opt); services.AddDbContext <TContext>(builder => builder.UseNpgsql(opt.ConnectionString)); } else if (!string.IsNullOrWhiteSpace(opt.ConnectionName)) { EfCoreOptionsRegistrar.Register <TContext>(opt); services.AddDbContext <TContext>((provider, builder) => builder.UseNpgsql(provider.GetService <IConfigurationRoot>().GetConnectionString(opt.ConnectionName))); } else { throw new InvalidOperationException("Connection name or string cannot be empty."); } }); return(context); }
/// <summary> /// Use EntityFramework Core with MySql /// </summary> /// <param name="context"></param> /// <param name="optAct"></param> /// <typeparam name="TContextService"></typeparam> /// <typeparam name="TContextImplementation"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException"></exception> public static IDbContextConfig UseEfCoreWithMySql <TContextService, TContextImplementation>( this DbContextConfig context, Action <EfCoreOptions> optAct = null) where TContextService : IEfContext where TContextImplementation : DbContext, TContextService { if (context is null) { throw new ArgumentNullException(nameof(context)); } var opt = new EfCoreOptions(); optAct?.Invoke(opt); context.RegisterDbContext(services => { if (!string.IsNullOrWhiteSpace(opt.ConnectionString)) { services.AddDbContext <TContextService, TContextImplementation>(o => o.UseMySql(opt.ConnectionString)); } else if (!string.IsNullOrWhiteSpace(opt.ConnectionName)) { services.AddDbContext <TContextService, TContextImplementation>((p, o) => o.UseMySql(p.GetService <IConfigurationRoot>().GetConnectionString(opt.ConnectionName))); } else { throw new InvalidOperationException("Connection name or string cannot be empty."); } }); return(context); }
/// <summary> /// 初始化数据上下文 /// </summary> /// <param name="config">数据上下文配置信息</param> private static void DbContextInit(DbContextConfig config) { if (!config.Enabled) { return; } DbContextInitializerBase initializer = CreateInitializer(config.InitializerConfig); DbContextManager.Instance.RegisterInitializer(config.ContextType, initializer); }
/// <summary> /// 重置数据配置信息 /// </summary> /// <param name="config">原始数据配置信息</param> /// <returns>重置后的数据配置信息</returns> public DataConfig Reset(DataConfig config) { //没有上下文,添加默认上下文 if (!config.ContextConfigs.Any()) { DbContextConfig contextConfig = GetDefaultDbContextConfig(); config.ContextConfigs.Add(contextConfig); } return(config); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Autofac Container var builder = new ContainerBuilder(); // DbContext DbContextConfig.Register(services, Configuration); // Autofac AutofacConfig.Register(builder); // AutoMapper AutoMapperConfig.Register(builder); // Identity services.AddDbContext <AppIdentityDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <IdentityUser>() .AddEntityFrameworkStores <AppIdentityDbContext>(); // MVC services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc(options => { //options.Filters.Add(typeof(GlobalExceptionFilter)); //options.ModelBinderProviders.Insert(0, new DateTimeUtcModelBinderProvider()); }) .AddJsonOptions(x => { x.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; x.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Build Autofac Service Provider builder.Populate(services); var container = builder.Build(); _serviceProvider = new AutofacServiceProvider(container); return(_serviceProvider); }
/// <summary> /// 开始初始化数据库 /// </summary> /// <param name="config">数据库配置信息</param> public virtual void Initialize(DataConfig config) { //没有上下文,添加默认上下文 if (!config.ContextConfigs.Any()) { DbContextConfig contextConfig = GetDefaultDbContextConfig(); config.ContextConfigs.Add(contextConfig); } foreach (DbContextConfig contextConfig in config.ContextConfigs) { DbContextInit(contextConfig); } }
public static void Main(string[] args) { //Serilog日志框架配置 SerilogLogConfig.DoConfig(); var webHost = CreateWebHostBuilder(args).Build(); using (var scope = webHost.Services.CreateScope()) { //数据初始化 DbContextConfig.DbInit(scope); } webHost.Run(); }
//public IConfigCreator<IExceptionHandler> ExceptionHandler { get; private set; } //public IConfigCreator<IExceptionHandler> ReLogOnHandler { get; private set; } //public IConfigCreator<IExceptionHandler> ErrorPageHandler { get; private set; } //public IConfigCreator<IExceptionHandler> ToolkitHandler { get; private set; } //public IConfigCreator<IExceptionHandler> ErrorOpeartionHandler { get; private set; } private void ConfigDatabase(WebAppXml xml) { if (xml.Databases != null) { bool entity = false; foreach (var item in xml.Databases) { if (item.Default) { TkDebug.Assert(fDefault == null, string.Format(ObjectUtil.SysCulture, "{0}的Default属性标识为True,而前面已经有配置Default为True了,配置错误", item.Name), this); fDefault = item; } if (!string.IsNullOrEmpty(item.ProviderName)) { entity = true; } fDictionary.Add(item.Name, item); } if (fDefault == null && xml.Databases.Count > 0) { fDefault = xml.Databases[0]; } if (entity) { //Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath); //var connectionStrings = config.ConnectionStrings.ConnectionStrings; //bool isModify = false; //var entities = from item in xml.Databases // where !string.IsNullOrEmpty(item.ProviderName) // select item; //foreach (var item in entities) //{ // ConnectionStringSettings setting = new ConnectionStringSettings(item.Name, // item.ConnectionString, item.ProviderName); // int index = connectionStrings.IndexOf(setting); // if (index == -1) // { // isModify = true; // connectionStrings.Remove(setting.Name); // connectionStrings.Add(setting); // } //} //if (isModify) // config.Save(ConfigurationSaveMode.Modified); } } }
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); string schema = "Contoso"; if (OperatingSystem.IsMacOs()) { schema = null; } var config = new DbContextConfig(); config.SecureApplicationContextConfig(modelBuilder, schema); config.ApplicationContextConfig(modelBuilder, schema); }
/// <summary> /// 获取数据库连接字符串的名称 /// </summary> /// <returns>数据库连接字符串对应的名称</returns> private static string GetConnectionStringName() { DbContextConfig contextConfig = GetDbContextConfig(); if (contextConfig == null || !contextConfig.Enabled) { return(typeof(TDbContext).ToString()); } string name = contextConfig.ConnectionStringName; if (ConfigurationManager.ConnectionStrings[name] == null) { throw new InvalidOperationException(Resources.DbContextBase_ConnectionStringNameNotExist.FormatWith(name)); } return(name); }
/// <summary> /// 重置数据配置信息 /// </summary> /// <param name="config">原始数据配置信息</param> /// <returns>重置后的数据配置信息</returns> public DataConfig Reset(DataConfig config) { //没有上下文,添加默认上下文 if (!config.ContextConfigs.Any()) { DbContextConfig contextConfig = GetDefaultDbContextConfig(); config.ContextConfigs.Add(contextConfig); } //如果业务上下文存在开启数据日志功能,并且日志上下文没有设置,则添加日志上下文 //if (config.ContextConfigs.All(m => m.ContextType != typeof(LoggingDbContext))) //{ // DbContextConfig contextConfig = GetLoggingDbContextConfig(); // config.ContextConfigs.Add(contextConfig); //} return(config); }
/// <summary> /// 获取数据库连接字符串的名称 /// </summary> /// <returns>数据库连接字符串对应的名称</returns> private static string GetConnectionStringName() { DbContextConfig contextConfig = GetDbContextConfig(); if (contextConfig == null || !contextConfig.Enabled) { return(typeof(TDbContext).ToString()); } string name = contextConfig.ConnectionStringName; if (ConfigurationManager.ConnectionStrings[name] == null) { throw new InvalidOperationException("名称为“{0}”的数据库连接串不存在".FormatWith(name)); } return(name); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //跨域设置 services.AddCors(options => options.AddPolicy("cors", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()) ); //数据库上下文配置 DbContextConfig.DoConfig(services, Configuration["Root:Database:ConnectionString"]); //配置身份服务器与内存中的存储,密钥,客户端和资源 services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(IdentityServer4Resources.GetIdentityResources()) .AddInMemoryApiResources(IdentityServer4Resources.GetApiResources()) .AddInMemoryClients(IdentityServer4Resources.GetClients()) .AddResourceOwnerValidator <LoginValidator>() //添加自定义验证类 .AddProfileService <ProfileService>(); services.AddAuthentication("Bearer") //添加授权模式 .AddIdentityServerAuthentication(Options => { Options.Authority = "http://localhost:5000"; //授权服务器地址 Options.RequireHttpsMetadata = false; //没有证书,不启用https Options.ApiName = "api"; //指定ApiName与Config配置中的相同 }); //添加Mvc服务到DI容器 services.AddMvc(); //添加跨域服务到DI容器 services.AddCors(); //将Options注入到DI容器 services.AddOptions(); services.Configure <AppsettingDataModel>(Configuration.GetSection("Root")); //Http请求访问器注入到DI容器 services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSignalR(); //业务逻辑注入到DI容器 IocConfig.DoDependencyInjection(services); //创建Redis单例实例 //RedisConfig.CreateInstance(Configuration["Root:Redis:Host"], Configuration["Root:Redis:PreKey"]); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var builder = new ContainerBuilder(); // Register your MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); // OPTIONAL: Register model binders that require DI. builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase. builder.RegisterModule <AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages. builder.RegisterSource(new ViewRegistrationSource()); // OPTIONAL: Enable property injection into action filters. builder.RegisterFilterProvider(); builder.RegisterType <BaseRepository <Address, SchoolDbContext> >().As <IRepository <Address> >(); builder.RegisterType <BaseRepository <School, SchoolDbContext> >().As <IRepository <School> >(); builder.RegisterType <BaseRepository <Student, SchoolDbContext> >().As <IRepository <Student> >(); builder.RegisterType <SchoolQueryService>().As <ISchoolQueryService>(); var connectionString = ConfigurationManager.ConnectionStrings["SchoolDbConnection"].ConnectionString; var dbContextConfiguration = new DbContextConfig( connectionString, typeof(SchoolDbContext), new MigrateToLatestVersion(new SampleDataSeeder())); builder.AddDataOnion(dbContextConfiguration); // Set the dependency resolver to be Autofac. var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
/// <summary> /// 开始初始化数据库 /// </summary> /// <param name="config">数据库配置信息</param> public virtual void Initialize(DataConfig config) { //没有上下文,添加默认上下文 if (!config.ContextConfigs.Any()) { DbContextConfig contextConfig = GetDefaultDbContextConfig(); config.ContextConfigs.Add(contextConfig); } //如果业务上下文存在开启数据日志功能,并且日志上下文没有设置,则添加日志上下文 if (config.ContextConfigs.All(m => m.ContextType != typeof(LoggingDbContext))) { DbContextConfig contextConfig = GetLoggingDbContextConfig(); config.ContextConfigs.Add(contextConfig); } foreach (DbContextConfig contextConfig in config.ContextConfigs) { DbContextInit(contextConfig); } }
/// <summary> /// 获取TomNet框架数据上下文配置 /// </summary> /// <returns></returns> private static DbContextConfig GetDbContextConfig() { return(_contextConfig ?? (_contextConfig = TomNetConfig.Instance.DataConfig.ContextConfigs .FirstOrDefault(m => m.ContextType == typeof(TDbContext)))); }