top of page
Search
Writer's pictureAndrew Boyd

Don't use Configuration!

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 configuration 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 the type 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).

6 views0 comments

Recent Posts

See All

Don't use ILogger

In a project recently, I noticed while ILogger was being passed into API controllers, it wasn't being used as much as it should, so I...

Development Frustrations

I got to do some React work this week, which has been an educational experience, a lot went wrong that shouldn't have and I learnt a few...

Comments


Post: Blog2_Post
bottom of page