protected DbContextTests() { var cfgHelper = new ConfigurationHelper(); var dbOptions = cfgHelper.Get <DbOptions>("Db"); dbOptions.Modules.ForEach(m => { //数据库名称转小写 m.Database = m.Database.ToLower(); m.EntityTypes = typeof(BlogDbContext).Assembly.GetTypes().Where(t => t.IsClass && typeof(IEntity).IsImplementType(t)).ToList(); }); var dbContextOptions = new MySqlDbContextOptions(dbOptions, dbOptions.Modules.First(), null, new LoginInfo()); DbContext = new BlogDbContext(dbContextOptions); //删除数据库 try { using var con = DbContext.NewConnection(); con.Execute("DROP DATABASE nm_blog;"); } catch { // ignored } //创建数据 DbContext.CreateDatabase(); //创建分类 AddCategory(); }
public static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { configHost.AddEnvironmentVariables(); }) .ConfigureServices((hostContext, services) => { var cfgHelper = new ConfigurationHelper(); var dbOptions = cfgHelper.Get <DbOptions>("Db", hostContext.HostingEnvironment.EnvironmentName); //日志工厂 var loggerFactory = dbOptions.Logging ? services.BuildServiceProvider().GetService <ILoggerFactory>() : null; dbOptions.Connections[0].EntityTypes = new List <Type> { typeof(AreaEntity) }; var dbContextOptions = new MySqlDbContextOptions(dbOptions, dbOptions.Connections[0], loggerFactory, null); services.AddSingleton <IDbContext>(new CommonDbContext(dbContextOptions)); services.AddSingleton <IUnitOfWork <CommonDbContext>, UnitOfWork <CommonDbContext> >(); services.AddSingleton <IAreaRepository, AreaRepository>(); services.AddSingleton <IAreaService, AreaService>(); services.AddSingleton <IAreaCrawlingHandler, AreaCrawlingHandler>(); var config = new MapperConfiguration(cfg => { new MapperConfig().Bind(cfg); }); services.AddSingleton(config.CreateMapper()); services.AddHostedService <Startup>(); Console.WriteLine("注入服务完成"); }) .UseLogging() .Build(); Console.WriteLine("准备启动"); host.Start(); host.WaitForShutdown(); }