.NET Core — Configuration/Settings binding

Simple settings and configurations for your application layer using dependency injection

I wanted to share with you a setup I use for binding settings using dependency injection in .NET Core.

In my application I have two types of repositories, one is a SQL repository and the second is the Azure Storage Repository (this can also apply to your services etc)

Both of these need connection strings and various things from the configuration.

So I implemented to following interfaces to access these settings.

Now in my application (in my case it’s an API), I add the following to my appsettings.json

Now we will create our WebSettings.cs file in our API project. This will collate all of settings in one place and will be implementing the IAzureStorageSettings and the IRepositorySettings interfaces.

Finally, we bind our configuration to our settings object and provide the setting WebSettings as a singleton for both IAzureStorageSettings and IRepositorySettings interface.

Let’s test out our settings by requesting the IAzureStorageSettings and IRepositorySettings via dependency injection.

public ValuesController(IAzureStorageSettings azureStorageSettings, IRepositorySettings repositorySettings)

{

var _azureStorageSettings = azureStorageSettings;

var _repositorySettings = repositorySettings;

}

Here we can see that both of these interfaces have been resolved and we can get the relevant information from them.

Reasons

The reason for setting it up this way is that we want to make sure that we keep our settings separated. The repository layers doesn’t need to know anything about the azure storage layer and vice-versa.

This applies to services and your UI layer too. Each layer should define it’s own interface for the things it needs to access. And in your application, you can implement these interfaces with the relevant configurations.