Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
I stumbled upon ConfigR a several months ago on twitter from Glenn Block. It uses ScriptCS (and Roslyn) and was developed by Adam Ralph.
I finally got around to take it for a test drive on a side project. It’s really a simple tool that I’ve been waiting for.
Why ConfigR?
The purpose of ConfigR is pretty straight forward. It allows you to write C# code to define configuration settings which you would normally place in a the appSettings section of a web.config/app.config. If you have used the appSettings at all, you probably wished they could be typed instead of always having to be strings. From Adam Ralph, the creator of ConfigRConfigR allows you to write your config in C# instead of XML – that’s really all there is to it. From that point on you can use your imagination to go wild in what you do in that C#.
Install via NuGet
Make sure your project is set to be using .NET 4.5 or greater You need to get ConfigR into your project. Install via the Package Manager in Visual Studio.PM> Install-Package ConfigROr if you prefer via the NuGet UI
Web Application
This portion has been updated to reflect the proper way of sing ConfigR with a web application. Thanks to creator Adam Ralph for clarification below in the comments.The default naming convention ConfigR uses to automatically load your configuration file is to look for a file in your output directly named Web.csx.
- Create a new file in your project named Web.csx
- Make sure the Copy to Output Directory is set to Do not copy.
This is different than a console app in which you do want to copy to output dir. In a web application, we want the Web.csx in the same location as you would normally see the web.config.
I’m going to create two simple configuration settings in our new Web.csx file
As you can expect the Add method is adding items into the ConfigR global configuraiton. The two configuration settings I’ve created are of different types: boolean and string.
Now in code when we need to access these configuration settings, it couldn’t be any easier.