ASP.NET 5 Configuration

So I've been playing around with ASP.NET 5 and of course I encountered the new configuration model. And a lot of things are nicely documented. But one thing I could not find on the internet (maybe I am just bad at binging/googling): how to get these configuration settings in your controller/viewmodel.

So what is the problem? For starter you setup your configuration(s) in the Startup class, for example:

public Startup(IHostingEnvironment env)
  var configuration = new Configuration().AddJsonFile("config.json");
  Configuration = configuration;

This code sets the configuration as the Startup class's Configuration property. This property is not easily accessible in your Controller, which is a good thing.

What?! A good thing? Yes, because it you should not use Configuration directly anywhere else. Dependency Injection to the rescue!

First thing you want to do is to think about which configuration settings you need (per viewmodel/controller), and then wrap this into a class:

public class MemConfig
  public string FromMem1 { get; }
  public string FromMem2 { get; }

This example will wrap two settings from configuration.

Now I want need these settings in my viewmodel (or controller, same technique), so we will add the MemConfig class to the viewmodel as a dependency:

private MemConfig mem;

public ConfigurationViewModel(MemConfig mem)
  this.mem = mem;

Now we only need to tell dependency injection how to create MemConfig. We do this again in the Startup class:

public void ConfigureServices(IServiceCollection services)
  services.AddSingleton<MemConfig>((isp) =>
   new MemConfig
      FromMem1 = Configuration["FromMem1"],
      FromMem2 = Configuration["FromMem2"]

So how does this work. Each time my controller needs a viewModel I make DI inject my viewmodel into the controller. The viewmodel also has a dependency, so DI will inject a MemConfig instance into the viewmodel.

I configured DI to use a singleton instance for the MemConfig class, and I told it how it should be initialized from Configuration. This last part is centralized in the Startup class, and we don't need any specific configuration logic anywhere else.