With System.Configuration.dll, we can add custom configSections into either App.config or Web.config files so that we can utilise strongly-typed configuration objects. On the other hand, .NET Core applications have replaced those App.config or Web.config with appsettings.json, which is more convenient for developers to use, especially for dependency injection (DI). In this post, we are going to walkthrough how we can deserialise the appsettings.json for DI purpose.


When we create an ASP.NET Core web application, we have a basic appsettings.json file looking like:

This is loaded up and built as an IConfiguration instance in Startup.cs. If we want to access to values, we simply call like:

This is good for fast application prototyping purpose, in general. However, if we need strongly-typed objects for those configurations, this is not ideal. How can we get the strongly typed objects then? Let’s have a look.

.NET Core RC1/RC2 Applications

Microsoft.Extensions.Configuration used to provide an extension method called Get(string key). With this method, we can easily deserialise appsettings.json object to an object of type T. Let’s say we have the AuthenticationSettings class representing the authentication section in appsettings.json. This is a sample code:

Now we have the auth instance to be injected wherever we want by:

.NET Core Applications

In .NET Core applications, unfortunately, the Get(string key) extension method has been removed. Instead, Microsoft.Extensions.Configuration.Binder provides another extension method called Bind(object instance). This actually binds an instance with the configuration value. Therefore, in order to have the same development experience as RC1/RC2, we should implement an extension method by ourselves like:

By implementing this extension method, we do the same approach as what we used to do in RC1/RC2 like above.

So far, we have briefly looked how we can deserialise appsettings.json on .NET Core applications for injection use. This would be useful for our robust application development.

Application Development and Integration
, ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: