简体   繁体   中英

Access from class library to appsetting.json or config.json in vNext

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;
}

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.

eg

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM