c# - 重新加载/重新启动 ASP.NET Core 2.1 Web 应用程序
问题描述
我有一个 .NET Core 2.1 Web 应用程序,用户可以在其中选择他们选择的数据库提供程序。它可以在 SQL Server、SQLite 和 MySQL 之间进行选择(目前,以后可能会添加更多提供程序)。我将用户的选择与每个数据库提供程序的连接字符串一起保存到 json 文件中:
"ConnectionStrings": {
"MSSQL": "Server=(localdb)\\MSSQLLocalDB;Database=ABC_db;Trusted_Connection=True;MultipleActiveResultSets=true",
"SQLite": "Data Source=ABC.db"
},
"UserSettings": {
"DatabaseProvider": "MSSQL", //this changes as per user's selection
"GenerateDb": false //this will be false for the first time, after that it will be true
}
在我的ConfigureServices
方法中,Startup.cs
我进行了一些检查以注册/注入数据库上下文和身份:
GenerateDb = Configuration.GetValue<bool>("GenerateDb");
DatabaseProvider = Configuration.GetValue<string>("SystemSettings:SystemProfile:DatabaseProvider");
if(GenerateDb)
{
if (DatabaseProvider == "MSSQL")
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString(DatabaseProvider)));
else if (DatabaseProvider == "SQLite")
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString(DatabaseProvider)));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
}
并且此代码按预期工作,它使用用户选择的任何提供者设置数据库上下文。唯一的问题是,要激活数据库上下文,我必须停止并再次启动应用程序,所以当它读取 json 文件时,它GenerateDb
是真的。我正在寻找可以帮助我重新启动应用程序而无需手动执行的东西。这个功能可用吗?我在文档中找不到任何内容。
解决方案
一个选项是注册 2 个不同的实现ApplicationDbContext
。
首先,创建新类(它们可以是空的实现,没关系)
public class SQliteApplicationDbContext : ApplicationDbContext {}
public class SqlServerApplicationDbContext : ApplicationDbContext {}
然后像这样注册它们:
services.AddDbContext<SqlServerApplicationDbContext >(options =>
options.UseSqlServer(Configuration.GetConnectionString(DatabaseProvider)));
services.AddDbContext<SQliteApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString(DatabaseProvider)));
services.AddScoped<ApplicationDbContext>((ctx) =>
{
// fyi: would be better to implement the options pattern here
DatabaseProvider = Configuration.GetValue<string>("SystemSettings:SystemProfile:DatabaseProvider");
if (DatabaseProvider == "MSSQL")
ctx.GetService<SqlServerApplicationDbContext >();
else if (DatabaseProvider == "SQLite")
ctx.GetService<SQliteApplicationDbContext>();
else
throw new Exception("Bad configuration");
});
请注意,这假设 asp.net 核心被配置为监视json
文件中的更改。
推荐阅读
- javascript - 当 DOM style="display:block; 使用 selenium/js 时,有什么方法可以获取元素的文本
- crystal-reports - Crystal Report - 将页脚抑制到最后一页 - 在其他页面上创建空白区域
- python - Python/Flask:有没有办法生成密码提示而不是制作整个用户平台?
- python - Unity POST 到本地主机的请求
- sql - 索引是否会影响 where is not null 查询的性能?
- react-native - undefined 不是对象(评估 '_expo.default.Localization.locale')
- python - IBM 语音转文本用户名和密码问题
- javascript - XMLHttpRequest:如何导航“链接”标头
- spring - 使用 Spring 配置从 Spring 连接到 WebSphere MQ
- python - 无法解决 LinAlgError:数组的最后 2 个维度必须是正方形