簡體   English   中英

使用從appsettings.json到startup.cs的連接字符串

[英]Using connection string from appsettings.json to startup.cs

目前在Startup中,我的sql server字符串如下所示:

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=servername;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true";
    services.AddDbContext<CRAMSContext>(options => options.UseSqlServer(connection));
}

我如何使用appsettings.json中的內容:

{
  "Data": {
    "DefaultConnection": {
    "ConnectionString": "Data Source=server;Initial Catalog=database;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

在新的ASP.NET 1.0 CORE新設置中看起來像這樣看起來像這樣參數化:

public void ConfigureServices(IServiceCollection services)
{
    var connection2 = new SqlConnection connectionString;
    services.AddDbContext<CRAMSContext>(options => options.UseSqlServer(connection2));
}

另外,如果我有一個不同的測試數據庫和qa,我如何知道ASP.NET應用程序是否為每個環境使用連接?

我的啟動類已經在根目錄中定義如下:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

使用適當的連接字符串結構:

{
  "ConnectionStrings": {
    "DefaultConnection": "xxx"
  }
}

在startup.cs中訪問:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM