簡體   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