首页 > 解决方案 > 重新加载/重新启动 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是真的。我正在寻找可以帮助我重新启动应用程序而无需手动执行的东西。这个功能可用吗?我在文档中找不到任何内容。

标签: c#datacontextasp.net-core-2.1

解决方案


一个选项是注册 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文件中的更改。


推荐阅读