Reputation: 14937
I am creating a Nuget Package and I'm working in my class library. I need access to appsetting.json or config.json to access to default connection string.
What is the best way to migrate my actual working code to the new version of ASP.NET vNext?
I have read about it in this question, but it's a fine solution for me.
Working code:
/// <summary>
/// Retrieves the default connectionstring from the App.config or Web.config file.
/// </summary>
/// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
public static string GetDefaultConnectionString()
{
return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString;
}
Upvotes: 7
Views: 6533
Reputation: 7542
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");
Upvotes: 5