Castle windsor is a really good library of IoC, but has some issues that sometimes can lead to obscure configuration. One of the most important is the concept of a “default component” suppose I create an ICache interface and I want some objects to be “cache-enabled”. My approach is usually that of a NullObject pattern, I build a NullCache component that does not store any object and always return null when we ask for an object in the cache. This is usually good because the code should not check for null when deal with a cache. Another way to use this component is to use decorator pattern to create component with cache and component with no cache, but for some objects I really need the cache object to be part of the real implementation.
As example I have a IPageDownloader interface that simply download a page, I create my concrete instance and I use cache to check if a page is in cache, and then issue a request with ETag HttpHeader to check if the page is really changed. The obvious Windsor configuration can be the following.
The order of declaration is important, because if someone forget to declare explicitly the dependency, the kernel usually gets the first reference that is found in the configuration. This is the declaration of the element that uses cache.
But I like to have the concept of default component explicitly set in the configuration, for example I want NullCache to be the default cache that all objects will use if the user does not set explicitly in configuration file. How can you accomplish this? First of all add a parameter to the configuration of the default object
Look at the default attribute, this is not an attribute that castle understands, so we need to build a facility that will use it.
This is a very simple facility, it adds a subresolver to the standard resolver, then he scan all defined models (with an handler to the ComponentRegistered event), you can check for optional attributes in the Attributes property of the Configuration object of a componentModel, for each “default” component I store the service type and the model in a dictionary, and the same dictionary is passed to the DefaultComponentResolver that really does the work.
the interesting part is in the line 14 where I check if I need to set the dependency manually, I first check that the DependencyType is a Service, then that the parameters on the model is null, this because I must be sure that the user does not set explicitly a component reference, and finally that my dictionary contains the service type, this means that I have a default component for that type. If all conditions are true it means that this dependencies is a service, is not set in configuration and has a default, so I want to resolve myself. In the Resolve method I simply delegate the kernel to resolve the default component for me and the game is done