7

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;
}
Community
  • 1
  • 1
chemitaxis
  • 13,889
  • 17
  • 74
  • 125
  • I have this same scenario (MVC project running, but all data access done in separate project, which should be reading the connection string from the web project). I don't see the answer below as "accepted", is this still not working for you? – ganders Jan 14 '16 at 20:27

1 Answers1

5

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");
devfric
  • 7,304
  • 7
  • 39
  • 52
  • 1
    Hi, this is for a web project... I'm in a class library vNext – chemitaxis Dec 14 '15 at 10:10
  • mmm ok, I'm trying right now... but, when I use it as Nuget, waht project.json is going to read? Thanks! – chemitaxis Dec 14 '15 at 10:15
  • 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. I am copying this code from my class library code, which works. I'll amend my original answer to make it easier – devfric Dec 14 '15 at 10:17
  • Ok, I understand ;) Thanks... But now, when I try to use Configure, I have an error, Configuration is a type, which is not valid in the given context... any idea? – chemitaxis Dec 14 '15 at 10:19
  • public static string GetDefaultConnectionString() { return Configuration["Data:MyDb:ConnectionString"]; } – chemitaxis Dec 14 '15 at 10:19
  • try return Configuration.Get("Data:MyDb:ConnectionString"); – devfric Dec 14 '15 at 10:23
  • Nop, I have other error :( It (get method) hasn't typed parameter...@firste – chemitaxis Dec 14 '15 at 11:31
  • Hi @firste and thanks for yout time, check that I have a static method where I need to obtain the value of Configuration... – chemitaxis Dec 14 '15 at 11:34
  • @chemitaxis: You can just define `Configuration` as `static`: `public static IConfigurationRoot Configuration;` instead of `public IConfigurationRoot Configuration { get; set; }`. Alternatively you can use directly `new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()["Data:MyDb:ConnectionString"]` in your code. – Oleg Dec 14 '15 at 12:02
  • Nop, I cant use get of Configuration if I do it static... WTF :( – chemitaxis Dec 14 '15 at 12:10