With the new ASP.NET 5 doing away with web.config, and thus the ConfigurationManagement namespace, I was trying to figure out how to read the connection string from my data access layer project in my MVC application.
Researching this issue, everything I've found says to just read the config value from the project.json configuration file in the Startup.cs file like this:
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();
//////
var connString = configuration.Get("Data:DefaultConnection:ConnectionString");
But I don't want my web project having anything to do with the data access. So, how does my data access layer project retrieve the connection string in this setup?
Update: Here's my startup.cs file and the ConfigureServices method:
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";
});
}
And here's my DataAccessLayer project, and my RepoBase.cs class
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;
}
}
This is where I'm drawing a blank as to how to retrieve my ApplicationOptions object in my DAL project, or just read the connectionstring value that is set in the Startup.cs
configuration.AddEnvironmentVariables()
method call.
Update 2: Oh, is this what I need to use from my Data Access Layer to access the environment variables: https://github.com/aspnet/configuration/blob/master/src/Microsoft.Extensions.Configuration.EnvironmentVariables/EnvironmentVariablesConfigurationProvider.cs