Asp.net-Core

從 ASP.net Core 2 MVC 應用程序中的 appSettings.json 儲存/檢索 ConnectionString

  • January 10, 2020

我正在尋找將連接字元串儲存在 .net Core 2 MVC 應用程序中的 appsettings.json 中的最佳實踐方法(就像您在 MVC 5 中的 web.config 中所做的那樣)。

我想使用 Dapper 而不是 EF(我發現了很多 EF 範例)。

像這樣的東西:

{
 "ConnectionStrings": {
   "myDatabase": "Server=.;Database=myDatabase;Trusted_Connection=true;"
 },

 "Logging": {
   "IncludeScopes": false,
   "LogLevel": {
     "Default": "Warning"
   }
 }
}

網上肯定有很多例子嗎?我找不到任何適用於 .net core 2.0 的內容。

1 和 2 之間發生了一些變化,我想確保我使用的是版本 2 最佳實踐。

我找到了這個 - 但它似乎是 .net core 1: Visual Studio 2017 - MVC Core - Part 05 - Connection String from appsettings.json

這使用鍵值對 appsettings - 而不是連接字元串: Read AppSettings in ASP.NET Core 2.0

同樣不清楚這是 .net Core 1 還是 2:Net Core Connection String Dapper Visual Studio 2017

在中定義您的連接字元串appsettings.json

{
   "connectionStrings": {
       "appDbConnection": "..."
   }
}

在 Startup 上閱讀它的價值

如果您遵循約定並在 下定義連接字元串connectionStrings,則可以使用擴展方法GetConnectionString()讀取其值。

public class Startup
{
   public IConfiguration Configuration { get; private set; }

   public Startup(IConfiguration configuration)
   {
       Configuration = configuration;
   }

   public void ConfigureServices(IServiceCollection services)
   {
       // Since you said you're using Dapper, I guess you might want to
       // inject IDbConnection?
       services.AddTransient<IDbConnection>((sp) => 
           new SqlConnection(this.Configuration.GetConnectionString("appDbConnection"))
       );

       // ...
   }
}

在儲存庫中使用 IDbConnection?

public interface ISpecificationRepository
{
   Specification GetById(int specificationId);
}

public SpecificationRepository : ISpecificationRepository
{
   private readonly IDbConnection _dbConnection;

   public SpecificationRepository(IDbConnection dbConnection)
   {
       _dbConnection = dbConnection;
   }

   public Specification GetById(int specificationId)
   {
       const string sql = @"SELECT * FROM [YOUR_TABLE]
                            WHERE Id = @specId;";

       return _dbConnection
           .QuerySingleOrDefault<Specification>(sql,
               new { specId = specificationId });
   }
}

只需要 POCO 中的連接字元串嗎?

您可以使用選項模式

  1. JSON定義一個與appsettings.json 中的對象結構完全匹配的類
public class ConnectionStringConfig
{
   public string AppDbConnection { get; set; }
}
  1. 在啟動時註冊該配置
public void ConfigureServices(IServiceCollection services)
{
  // ...

  services.Configure<ConnectionStringConfig>(
      this.Configuration.GetSection("connectionStrings")
  );

  // ...
}
  1. 在您的 POCO 中接收訪問器
public class YourPoco
{
   private readonly ConnectionStringConfig _connectionStringConfig;

   public YourPoco(IOptions<ConnectionStringConfig> configAccessor)
   {
       _connectionStringConfig = configAccessor.Value;

       // Your connection string value is here:
       // _connectionStringConfig.AppDbConnection;
   }
}

筆記:

  1. 請參閱我的範常式式碼,了解如何在 Core 1.x 和 2.0 上從 appsettings.json 讀取值。
  2. 如果您有超過 1 個連接字元串,請查看我如何設置。

只需將如下所示的內容放入 appsettings.json 中。

"ConnectionStrings": {
   "DefaultConnection": "Data Source=;Initial Catalog=;Persist Security Info=True;User ID=; Password=;"
}

在 Startup.cs 中獲取它,如下所述:

public class Startup
{
   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);

       builder.AddEnvironmentVariables();
       Configuration = builder.Build();
   }

   public IConfigurationRoot Configuration { get; }
}

使用依賴注入在控制器中註入配置,如下所述:

public class MyController : Controller
{
   private readonly IConfiguration _configuration;
   private string connectionString;

   public MyController(IConfiguration configuration) 
   {
       _configuration = configuration;

       connectionString = _configuration.GetConnectionString("DefaultConnection");
   }
}

引用自:https://stackoverflow.com/questions/50507382