Make configuration strongly-typed in ASP.NET Core

Well if you familiar with ASP.NET Core, you probably know about IOptions<T> and how easy it is to bind classes to configuration sections, however, there is an easier way to make configuration strongly-typed ASP.NET Core.

The typical IOptions<T> configuration looks something like below. Remember you need to reference Microsoft.Extensions.Options.ConfigurationExtensions.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddOptions();
    services.Configure<YOURCLASS>(Configuration.GetSection("YOURCLASS"));
}

This seems to solve lots of messiness that we had in classic ASP.NET, but still, the issue here is that you have to inject IOptions<T> to your constructor everytime you want to use it.

For most of the people, it might be OK, however, imagine you have a large project with lots of objects. You have to import the namespace and inject IOptions to your constructor.

The good news is that there might be a way to get around this:

public static class ServiceCollectionExtensions
{
    public static TConfig ConfigureSetting<T>(this IServiceCollection services, IConfiguration configuration) where T : class, new()
    { 
        var config = new T();
        configuration.Bind(config);
        services.AddSingleton(config);
        return config;
    }
}

By just creating an extension method on IServiceCollection and try to bind the config which comes from your POCO object you are able to register it on the DI container.

You have to call this from ConfigureServices in StartUp class:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.ConfigureSetting<YOURCLASS>(Configuration.GetSection("YOURCLASS"));
}

That’s all to it. Now you can inject your POCO object(YOURCLASS) to a constructor which magically resolves to your setting from app.setting.js.

You may also like...

Leave a Reply

Your email address will not be published.