获取数据访问层中的连接字符串

时间:2017-05-19 16:47:34

标签: asp.net-core

我有一个项目的分层架构如下。

MyProject.Web           <-- ASP.NET Core app
MyProject.BusinessLogic <-- Class Library
MyProject.DataAccess    <-- Class Library

Web项目引用BusinessLogic,后者又引用DataAccess

连接字符串存储在appsettings.json项目的Web中,如下所示。

{
  "ConnectionStrings": {
    "LocalDatabase": "Server=..."
  },
  // ...

  }
}

如何在DataAccess项目中获取连接字符串?

1 个答案:

答案 0 :(得分:1)

试试这个:

public static IConfiguration Configuration { get; set; }

private string GetConnectionString()
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");

    Configuration = builder.Build();

    return Configuration.GetConnectionString("DefaultConnection");

}

记住appsetting.json

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=((local));Database=database;Trusted_Connection=True;user id=xx;password=xxxx;"
  }
}