The old class library read config values automatically with the app.config. In the new class library you have to add this functionality. The Startup.cs is use to read the app.settings In a class library you have to add a Startup.cs also.
In your project.json
make sure you have the dependency
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
Add an appsettings.json
via add - new item
. Filter on json
{
"Data": {
"MyDb": {
"ConnectionString": "Server=.;Database=MyDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
}
You can call your connection MyDb or DefaultConnection.
Add a Startup.cs
to put the code to read the appsettings.json
.
See below for the Startup
constructor method doing this.
e.g.
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MyProject
{
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration["Data:MyDb:ConnectionString"]));
}
}
}
In the example above the reference
Configuration["Data:MyDb:ConnectionString]
will return a type of IConfigurationRoot, not string.
To get the string value try the following
string connection = Configuration.Get<string>("Data:MyDb:ConnectionString");