Thursday, February 04, 2010

Did you know that you can mix fluent and XML configuration for the same component. I’m not the only one who thinks XML component registration is a verbose pit of failure. But there are some things you really do not want to hard code into your application. Things like connection strings, the location of resources on the network and other deployment specific settings. Windsor provides a very nice story for setting property values on your components using an XML file without having to fall back on the awful appSettings or defining your own custom ConfigurationSection. Here’s how it’s done:

Let’s say we have a class ConfigurationThing with some string properties for configuring a database connection:

Notice that we’re also including registration configuration from the file windsor.config. Also note that we give our IConfigurationThing service a name: ‘configuration’. Now in the windsor.config file we can configure the properties of ‘configuration’ by referencing it’s name – except that in the config file it’s confusingly called ‘id’:

This is exactly the same as the standard XML component registration, except that we don’t specify the ‘service’ and ‘type’ attributes of the component. Windsor simply looks for a component registered with the same ‘id’… or rather ‘name’.

Now when we resolve our IConfigurationThing its properties are set to the values we specified in windsor.config:

Because Server, Database, User and Password are properties rather than constructor arguments, the component resolution will not fail if they are not supplied, instead they will all be null. This can be a nice feature if you want to supply default arguments that can be overridden by configuration.

I use this technique a lot. Configuration is one of those unexpected benefits of using Windsor.

Code Rant

Notepad, thoughts out loud, learning in public, misunderstandings, mistakes. undiluted opinions. I'm Mike Hadlow, an itinerant developer. I live (and try to work in) Brighton on the south coast of England. Please don't mistake me for an expert in anything. I love technology and programming, but make no claims to be any good at it. Much of what you read here may be poorly thought out, wrong, or just plain dangerous.