In my previous post Building Windows Azure Services Without Compromising Testability I demonstrated how the Unity Application Block can be used to build a testable Windows Azure Service. Since then I started to play with the ServiceLocator in order to introduce a new testable code base in a brownfield environment.
As many of colleagues would agree, the ServiceLocator is often considered to be an anti-pattern, but there are some scenarios where it shines. Introducing an Inversion of Control (IoC) container in a brownfield project is a scenario where the ServiceLocator can be leveraged in order to reduce risks.
When we start working on a brownfield project, the outcome of our modifications is usually quite unpredictable. Rewriting the entire code base is costly and very risky. The lack of documentation makes it hard for a team to rewrite modules without forgetting features and accounting for undocumented behavior. The ServiceLocator can be used to introduce the IoC container without significantly altering the structure of the application. We can start introducing the new code base in very targeted areas. Consequently, allowing us to bring the application under test. Furthermore it allows us to refactor and reorganize the architecture of the application from within. As the project evolves its important to keep in mind that as we overhaul the brownfield project, the ultimate goal is to factor out the ServiceLocator in order to keep the IoC Container confined to the application’s bootstrap. This of course is not something that can be achieved instantly, it takes time and planning.