As we're nearing the release date of Castle Windsor 3.0 (codename Wawel) I will be blogging about some of the new features and improvements introduced in the new version.
One of the features that were introduced in current version 2.5 was support for debugger diagnostic views in Windsor.
In Wawel one of the improvements is addition of a new diagnostic - detection of cases where the container is being used as Service Locator. For those unfamiliar with what Service Locator is, it's an approach that breaks the basic rule of Inversion of Control, by explicitly calling out to the container from within application.
Here's where I tell you Service Locator is bad
I spent last two days reading through the StackOverflow archive of IoC related questions and one of the most common sources of problems is that container is being used as Service Locator.
I wrote why Service Locator (particularly when implemented via IoC container) is a bad idea on few occasions (for example here). Also Mark has a good overview of drawbacks of this approach so I won't rehash it again.
Good news is - even if someone from your team starts using the container as Service Locator, Windsor will now help you detect those cases.
Here's where I give you an example
Take a look at the following class:
[Singleton]
public class ComponentFactory
{
private readonly IKernel kernel;
public ComponentFactory(IKernel kernel)
{
this.kernel = kernel;
}
public object Create(String name)
{
return kernel.Resolve<object>(name);
}
}
It is part of the application layer (and not infrastructure layer) and as such it should not be aware of the container, yet it depends on IKernel. Also quick look at its Create method is enough to see that it most likely is passed around throughout the application and used to pull components from the container without giving it much thought, which as you're surely guessing by now is a recipe for trouble.
Here's where I show you how it looks
If you navigate in debug mode to a container instance where components like the one described above exists a new entry in the debugger view will appear listing those components.

Here's where I tell you how it works
Windsor doesn't have the whole picture of your application, so it can only detect a subset of cases of Service Locator usage. In particular it is unable to detect the case when a Service Locator is built completely on top of the container as commonly found, where container is assigned to a public field of a static class and accessed through that field.
Since Windsor only knows about the components you register with it, it looks for components that depend on the container and are not extending infrastructure of the container itself (like for example Interceptors are). All such components are flagged as potential service locator and presented to you.
I hope you'll find this feature useful.
Here's where you tell me what you think
Posted
04-24-2011 11:41 AM
by
Krzysztof Koźmic