繁体   English   中英

重新加载/重新启动ASP.NET Core 2.1 Web应用程序

[英]Reload/Restart ASP.NET Core 2.1 web application

我有一个.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
  }

Startup.cs ConfigureServices方法中,我进行了一些检查以注册/注入数据库上下文和身份:

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为true。 我正在寻找可以帮助我无需手动执行就重新启动应用程序的东西。 此功能可用吗? 我在文档中找不到任何内容。

一种选择是注册ApplicationDbContext 2种不同实现。

首先,创建新的类(它们可以是空的实现,没关系)

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 core被配置为监视json文件中的更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM