The views and opinions expressed on this site are mine and do not necessarily reflect those of my employer

Don't use Configuration!

POSTED ON 10 July, 2020 BY ANDREW BOYD - 1 min read

One of the most used classes in .NET Core would have to be IConfiguration, found in the Microsoft.Extensions.Configuration Nuget package. You can access your config using Configuration["ASection:ConfigItem"]; or you can get your connection string with Configuration.GetConnectionString("SomeDatabase"). If you are dealing with strings, this is "ok", but what if you want to have a default value? What if you want to have typed configuration? Using this class starts to become a lot of hard work!

Enter the Nuget package: Microsoft.Extensions.Configuration.Binder. This is seriously one of your best friends! It supplies extension methods that allows you to retrieve typed values, for example Configuration.GetValue<int>("ASection:ConfigItem"); and if you want to set a default value then the previous bit of code becomes Configuration.GetValue("ASection:ConfigItem", 1); (you can ditch <int> because it is inferred from the default value's type). How great is that! A massive time saver!

As a side note, when setting up configuration, ask yourself the questions, What if someone deletes this configuration item? Is it acceptable that an exception is thrown?

Configuration examples:

  • Default number of records in a page returned in a resultset, it seems crazy that if someone removes this value from the config, that the entire system stops working.
  • A connection string, it would be crazy to define a default.

The key here is to give it some thought, not just to assume because you've put it in the AppSettings file, that it will always be in the AppSettings file.

So the next time you want to install IConfiguration, I strongly recommend not bothering with Microsoft.Extensions.Configuration, instead grab Microsoft.Extensions.Configuration.Binder, this will install Microsoft.Extensions.Configuration as it's a dependency and will give you the power of using types and hopefully will have you thinking about what the default value for your configuration should be (which is just a good idea).