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.
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 ConfigR
ConfigR 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 ConfigR
Or if you prefer via the NuGet UI
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.
Loading from Custom Location
Want to load a config file not using the default naming convention? Easy.
You can use complex types defined in your assembly or another referenced assembly. When using a referenced assembly, you must specify the ScriptCS reference directive to the DLL in bin/ directory.
Here is my type defined in another referenced project called AnotherProject.dll
Here is my new Web.csx. Again, note the #r ScriptCS reference directive and the using statement.
Now we can get our our complex type.