ASP.NET 5: New configuration files and containers

With ASP.NET vNext we get also new config files. Yes, files, because more than one config file format is supported. Our configuration can be JSON, INI or XML and I’m sure you can write configuration handlers that support your own custom formats. Also support for multiple configuration containers is here. In this posting I will show how new configuration system works in ASP.NET vNext.

Configuration files

Suppose we have three configuration files.

config.json

{
    "ConnectionStrings": {
        "JsonConnectionString": "json connection string"
    }
}

config.xml

<config>
    <ConnectionStrings>
        <XmlConnectionString>xml connection string</XmlConnectionString>
    </ConnectionStrings>
</config>

config.ini

[ConnectionStrings]
IniConnectionString = ini connection string

They all follow the same structure although formats are different.

Dependencies

Before we can load our config files we have to add some dependency definitions to project.config file:

{
    // ...

    "dependencies": {
        "Kestrel": "1.0.0-alpha4",
        "EntityFramework.SqlServer": "7.0.0-alpha4",
        // ...
        "Microsoft.AspNet.StaticFiles": "1.0.0-alpha4",
        "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-alpha4",
        "Microsoft.Framework.ConfigurationModel.Xml": "1.0.0-alpha4",
        "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-alpha4"
    }

    // ...
}

Having these dependencies to configuration model we can read configuration from JSON and INI files.

Loading configuration files

Something that I have not covered yet is how ASP.NET vNext applications are loaded. I don’t stop on this topic but just mention that there is class called Startup with method Configure(). In this method you add all services you need to your application. In this method we will also load configuration files.

public class Startup

{

    public void Configure(IApplicationBuilder app)

    {

        // Setup configuration sources

        var configuration = new Configuration();

        configuration.AddJsonFile(“config.json”);

        configuration.AddIniFile(“config.ini”);
        configuration.AddXmlFile(“config.xml”);

        configuration.AddEnvironmentVariables();

 

        // …

    }

}

Now we have configuration files loaded and it’s time to get read some config parameters from our powerful configuration object.

Reading configuration parameters

Now let’s read all these configuration params from configuration object. I used Watch window in Visual Studio to show values of parameters.

ASP.NET MVC 6: Values from multiple configuration files

If we want to read parameters of some other type than string then we can call generic version of Get() method:

var size = configuration.Get<int>(“Box:Size”);

Why multiple configurations

Why we need configuration system like this? Well, there are some new scenarios that are supported through this system:

  • we can use multiple configuration containers,
  • we can use same type of settings files in web and desktop programs.

To get better idea what I mean take a look at the following code.

// Common configuration

var configuration = new Configuration();

configuration.AddJsonFile(“config.json”);

configuration.AddIniFile(“config.ini”);

configuration.AddXmlFile(“config.xml”);

configuration.AddEnvironmentVariables();

 

// Mailer configuration

var emailConfiguration = new Configuration();

emailConfiguration.AddIniFile(“advanced-mailer.ini”);

 

// SMS configuration

var smsConfiguration = new Configuration();

smsConfiguration.AddXmlFile(“sms.config”);

Also you can use those configuration files in your custom components so developers who are using your components doesn’t have to load configurations in their code.

Wrapping up

We have now support for multiple configuration file formats and we can create as many configuration objects as we like. It’s easy to read values from configuration objects and we have even support for typed configuration settings. Supporting multiple configuration files and dealing with INI-files has never been so easy.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    5 thoughts on “ASP.NET 5: New configuration files and containers

    • January 8, 2015 at 11:23 pm
      Permalink

      This is not working for me. Here is my config file contents:

      {
      "Data": {
      "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-PBDeskCom.WebApp-b3918a28-23bf-4417-822c-d1ec3ba709f0;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
      },
      "EntityFramework": {
      "ApplicationDbContext": {
      "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
      }
      }
      }

      And i try to ready it as below

      var conf = new Microsoft.Framework.ConfigurationModel.Configuration();
      var source = new Microsoft.Framework.ConfigurationModel.JsonConfigurationSource("config.json");
      conf.Add(source);

      var x = conf.Get("Data:DefaultConnection:ConnectionString");

      Also tried Get(“DefaultConnection:ConnectionString”) but in any cases i am getting x as null.

    • August 12, 2015 at 4:42 am
      Permalink


      using Microsoft.Framework.Configuration;

      namespace Test
      {
      public class Startup
      {
      public static IConfiguration Configuration { get; set; }

      public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
      {

      // Setup configuration sources.
      var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
      .AddJsonFile(“config.json”)
      .AddEnvironmentVariables();
      Configuration = builder.Build();
      }

      // This method gets called by a runtime.
      // Use this method to add services to the container
      public void ConfigureServices(IServiceCollection services)
      {
      services.AddEntityFramework()
      .AddSqlServer()
      .AddDbContext(options =>
      {
      options.UseSqlServer(Configuration.Get(“Data:ConnectionString”));
      });

      services.AddMvc();
      }

      // Configure is called after ConfigureServices is called.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      // Configure the HTTP request pipeline.
      app.UseStaticFiles();

      // Add MVC to the request pipeline.
      app.UseMvc();
      }
      }
      }

    • Pingback:ASP.NET 5 multiple configurations without using environment variables | Software Engineering

    • December 29, 2015 at 7:40 pm
      Permalink

      Hello, did you have an example with ASP.NET 5 RC? Tks.

    • January 7, 2016 at 12:24 pm
      Permalink

      var builder = new ConfigurationBuilder()
      .AddEnvironmentVariables()
      .AddJsonFile(“config.json”)
      .AddJsonFile(“config.production.json”, true);

      if (env.IsDevelopment())
      {
      // This reads the configuration keys from the secret store.
      // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
      builder.AddUserSecrets();
      }

      Configuration = builder.Build();

    Leave a Reply

    Your email address will not be published. Required fields are marked *