Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net core how can I replace the Configuration Manager

I am new to ASP.NET Core RC2 and I was wondering how can I get some configuration settings and apply it to my method. For Instance in my appsettings.jsonI have this specific setting

"ConnectionStrings": {
    "DefaultConnection": 
        "Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"
  }

In my Controller every time I want to query the database I have to use this setup

 using (var conn = 
     new NpgsqlConnection(
         "Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"))
 {
     conn.Open();
 }

The obvious pitfull here is that if I want to add more to the configuration I have to change every single instance of that method. My question is how can I get the DefaultConnection in the appsettings.json so that I can do something like this

 using (var conn = 
     new NpgsqlConnection(
         ConfigurationManager["DefaultConnection"))
 {
     conn.Open();
 }
like image 896
user1591668 Avatar asked May 24 '16 23:05

user1591668


People also ask

Does .NET Core still use web config?

ASP.NET Core no longer uses the Global. asax and web. config files that previous versions of ASP.NET utilized.

Does ConfigurationManager work in .NET Core?

ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.

Where is the configuration stored in .NET Core?

In ASP.NET Core application, the configuration is stored in name-value pairs and it can be read at runtime from various parts of the application. The name-value pairs may be grouped into multi-level hierarchy.

How do I install configuration Manager?

Right Click on the References and select Add Reference... Now search for System. ConfigurationManager. Select it and this will add to your Project References.


2 Answers

In ASP.NET Core there are a lot of options you can use to access the configuration. It seems like if you're interesting it accessing the DefaultConnection you'd be better off using the DI approach. In order to ensure that you can use constructor dependency injection we have to correctly configure a few things in our Startup.cs.

public IConfigurationRoot Configuration { get; }

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

We have now read our configuration JSON from the builder and assigned it to our Configuration instance. Now, we'll need to configure it for dependency injection - so let's start by creating a simple POCO to hold the connection string.

public class ConnectionStrings
{
    public string DefaultConnection { get; set; }
}

We are implementing the "Options Pattern" where we bind strongly-typed classes to configuration segments. Now, in ConfigureServices do this:

public void ConfigureServices(IServiceCollection services)
{
    // Setup options with DI
    services.AddOptions();

    // Configure ConnectionStrings using config
    services.Configure<ConnectionStrings>(Configuration);
}

Now that this is all in place, we can simply require the constructor of the class to take on the IOptions<ConnectionStrings> and we'll be given a materialized instance of the class containing the configuration values.

public class MyController : Controller
{
    private readonly ConnectionStrings _connectionStrings;

    public MyController(IOptions<ConnectionString> options)
    {
        _connectionStrings = options.Value;
    }

    public IActionResult Get()
    {
        // Use the _connectionStrings instance now...
        using (var conn = new NpgsqlConnection(_connectionStrings.DefaultConnection))
        {
            conn.Open();
            // Omitted for brevity...
        }
    }
}

Here is the official documentation which I always suggest as a must read.

like image 83
David Pine Avatar answered Sep 25 '22 08:09

David Pine


ConfigurationManager.AppSettings
is available in .NET Core 2.0 after referencing NuGet package
System.Configuration.ConfigurationManager

like image 30
ZeeTen Nayak Avatar answered Sep 23 '22 08:09

ZeeTen Nayak