随着新的ASP.NET 5取消了web.config,从而取消了ConfigurationManagement命名空间,我试图弄清楚如何从我的MVC应用程序中的数据访问层项目中读取连接字符串。
研究这个问题,我发现的所有内容都只是从Startup.cs文件中的project.json配置文件中读取配置值,如下所示:
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();
//////
var connString = configuration.Get("Data:DefaultConnection:ConnectionString");
但我不希望我的网络项目与数据访问有任何关系。那么,我的数据访问层项目如何在此设置中检索连接字符串?
更新:这是我的startup.cs文件和ConfigureServices方法:
public void ConfigureServices(IServiceCollection services)
{
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add MVC services to the services container.
services.AddMvc();
// Register application services.
services.Configure<ApplicationOptions>(options =>
{
options.ConnectionString = "Data:DefaultConnection:ConnectionString";
});
}
这是我的DataAccessLayer项目和我的RepoBase.cs类
public class RepoBase
{
//private readonly string _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//private readonly string _connectionString = Environment.GetEnvironmentVariable("ConnectionString");
private readonly string _connectionString;
public RepoBase(IOptions<ApplicationOptions> appOptions)
{
this._connectionString = appOptions.ConnectionString;
// or just read directly from System.Configuration.Get("");
}
protected SqlConnection GetConnection()
{
var conn = new SqlConnection(_connectionString);
conn.OpenAsync();
return conn;
}
}
这是我在DAL项目中如何检索ApplicationOptions对象的空白,或者只是读取Startup.cs中设置的connectionstring值
configuration.AddEnvironmentVariables()
方法调用。
更新2:哦,这是我需要在数据访问层中使用来访问环境变量的内容:https://github.com/aspnet/configuration/blob/master/src/Microsoft.Extensions.Configuration.EnvironmentVariables/EnvironmentVariablesConfigurationProvider.cs
答案 0 :(得分:2)
这是this
的副本在ConfigureServices方法中,将配置对象添加为单例。
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton(_ => configuration);
}
然后像这样更新你的BaseRepo类
public class BaseRepo {
private readonly IConfigurationRoot config;
public BaseRepo(IConfigurationRoot config) {
this.config = config;
}
public static SqlConnection GetOpenConnection() {
var cs = config.Get<string>("Data:DefaultConnection:ConnectionString");
var connection = new SqlConnection(cs);
connection.Open();
return connection;
}
}