Getting Started with .NET Core

Getting Started with .NET Core

  • 2016-09-17
  • 1239

.NET Core has a new way of working with configuration that is much more flexible than the way that previous versions of .NET have.

It allows you to:

  1. Pull configuration from multiple sources and bring it in to one place.
  2. Easily map that configuration information into classes to make access easier.
  3. Override configuration from previous sources so that you can import a base configuration then override settings on per-environment basis.

This post will be concerned with the first of these: Pulling configuration from multiple sources and bringing it together in to one place. We’ll discuss the second and third aspect in future posts.

Getting Started

To use it you need to add the Microsoft.Extensions.Configuration NuGet package to your application.

Once you’ve imported the package your project.json will contain:

 "dependencies": {
    "Microsoft.Extensions.Configuration": "1.0.0",
    .... Other dependencies here ....
  }

From the basic configuration package you don’t really get much in the way of configuration sources, only the in-memory one is available. However, that’s just enough to show you the basic set up of the configuration in an application.

public class Program
{
    public static void Main(string[] args)
    {
        // Defines the sources of configuration information for the 
        // application.
        var builder = new ConfigurationBuilder()
            .AddInMemoryCollection(new []
            {
                new KeyValuePair("the-key", "the-value"),
            });

        // Create the configuration object that the application will
        // use to retrieve configuration information.
        var configuration = builder.Build();

        // Retrieve the configuration information.
        var configValue = configuration["the-key"];
        Console.WriteLine($"The value for 'the-key' is '{configValue}'");

        Console.ReadLine();
    }
}

The builder is the thing that allows you to set up the sources of configuration information. Each provider adds extension methods so you can add them easily to the builder. The InMemoryCollection simply takes an IEnumerable of KeyValuePairs to initialise its values.

Once you have set up your configuration sources you can build all that into an actual object you can use in your application, by calling Build() on the builder object. From here on you can access configuration values with indexer notation.

Adding a JSON File Source

So far, what we have isn’t very useful. We need to pull configuration information from outside the application such as a JSON file. To do that, we need to add another NuGet package. This one provides a JSON provider and is called Microsoft.Extensions.Configuration.Json.

Microsoft.Extensions.Configuration.Json NuGet package

We can now extend the simple application above by adding an appsettings.json file and adding in the code to build it.

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddInMemoryCollection(new []
    {
        new KeyValuePair("the-key", "the-value"),
    });

And the appsettings.json looks like this:

{
  "my-other-key": "my-other-value" 
}

And the value is retrieved like any other:

configValue = configuration["my-other-key"];
Console.WriteLine($"The value for 'my-other-key' is '{configValue}'");

However, while this looks like it should work, it won’t. When you added a settings file previously, Visual Studio would mark it for copying to the output folder so that the running application could find it. However, it doesn’t do that with .NET Core (yet – I do hope they add it).

Instead you get a FileNotFoundException, like this:

Exception Assistant showing a File Not Found Exception

To get the appsettings.json file added to the output folder you are going to have to modify the project.json file.

In the buildOptions section add copyToOutput with the name of the file. If there is more than one file you can put in an array of files rather than just the one. The top of the project.json file now looks like this:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "copyToOutput": "appsettings.json"
  },
  .... The rest of the file goes here ....

The next time the project is run it will copy the appsettings.json file and you won’t get an exception to say that the file was not found.

We got started by pulling in configuration data from multiple source in .NET Core, in this part we’ll look at mapping the configuration onto a set of classes so that is becomes easier to access.

This is something that is built into ASP.NET Core through dependency injection, so we’ll look at that.

In ASP.NET Core applications, the configuration is setup in the Startup class normally. It is added in the ConfigureServices method. There are two lines you need to add:

public void ConfigureServices(IServiceCollection services)
{
  services.AddOptions();
  services.Configure(GetConfiguration());
  // Other services are configured here.
}

In order to get them to compile you need an additional NuGet package called Microsoft.Extensions.Options.ConfigurationExtensions. This ensures that everything you need to have configuration converted to the type you specify is set up and that it can be dependency injected into your code.

The GetConfiguration() call is to get the generated IConfigurationRoot and looks similar to the way we set up the configuration int the previous post. For this example it looks like this:

private IConfigurationRoot GetConfiguration()
{
  var builder = new ConfigurationBuilder();

  builder.AddInMemoryCollection(new Dictionary<string, string>
  {
    { "InMemory", "This value comes from the in-memory collection" }
  });

  builder.AddEnvironmentVariables();
  builder.AddJsonFile("appSettings.json");

  return builder.Build();
}

I’ve added configuration from the environment variables as well.

As the app is configured to map the configuration settings to an object structure, here’s what it looks like:

public class MyConfiguration
{
  public string UserName { get; set; } // From the environment variable of the same name
  public string InMemory { get; set; } // From the in-memory collection
  public string RootItem { get; set; } // from appSettings.json
  public FavouriteStuff Favourites { get; set; } // from appSettings.json
  public string[] Fruits { get; set; } // from appSettings.json
}

public class FavouriteStuff
{
  public string TvShow { get; set; }
  public string Movie { get; set; }
  public string Food { get; set; }
  public string Drink { get; set; }
}

As you can see the structure can be deep if necessary which gives you quite a lot of flexibility.

The appSettings.json file looks like this:

{
  "RootItem": "This is at the root",
  "Favourites": {
    "TvShow": "Star Trek: The Next Generation",
    "Movie": "First Contact",
    "Food": "Haggis",
    "Drink":  "Cream Soda"  
  },
  "Fruits": [
    "Apples",
    "Oranges",
    "Pears",
    "Cherries",
    "Bananas",
    "Strawberries",
    "Raspberries"
  ]           
}

Now, the controller that needs the configuration information looks like this:

public class HomeController : Controller
{
    private readonly IOptions<MyConfiguration> _config;

    public HomeController(IOptions<MyConfiguration> config)
    {
        _config = config;
    }
    public IActionResult Index()
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        return new JsonResult(_config.Value, settings);
    }
}

All this does is take the MyConfiguration object created by the framework on our behalf and render it as JSON to the browser. The key parts are that the constructor takes an IOptions<MyConfiguration> reference, which you store in the controller and you can then access as needed in any of the methods of the controller.

Finally, the output in the browser looks as follows.

{
  "UserName": "colin.mackay",
  "InMemory": "This value comes from the in-memory collection",
  "RootItem": "This is at the root",
  "Favourites": {
    "TvShow": "Star Trek: The Next Generation",
    "Movie": "First Contact",
    "Food": "Haggis",
    "Drink": "Cream Soda"
  },
  "Fruits": [
    "Apples",
    "Oranges",
    "Pears",
    "Cherries",
    "Bananas",
    "Strawberries",
    "Raspberries"
  ]
}

It looks very similar to the appSettings.json file, but you can see that it has, in addition, the “UserName” and “InMemory” elements which don’t appear in that file.

Suggest

ASP NET Core (ASP NET 5),MVC 6,C#,Angular2 & EF Crash Course

Mastering ASP.NET and ADO.NET with C#

AngularJS For .Net Developers From Scratch

Learn ASP NET with Bootstrap, Entity Framework, JavaScript, C#

Complete ASP NET MVC Web Development - Newbie to Ninja!