(This is a continuation of a previous post)
In the previous post, we adapted our existing code to allow the use of an IoC Container, and prepared the container so it is ready to use. In this post, we put that foundation to work and start altering our logic.
Install Service Locator
When coding new applications, Inversion of Control (IoC) is best done using Dependency Injection, or DI. However, DI assumes all necessary classes are registered with the container and available for resolution. When converting an existing application, it is not practical to convert all necessary classes to DI in one step. Trying to do so can dramatically increase the scope of the work, making the conversion project more difficult and possibly extending it beyond a single sprint.
In order to avoid the requirement of converting the entire application at once, we introduce an intermediate step of using a Service Locator. Using the Service Locator pattern allows you to convert objects to the IoC pattern slowly over time instead of requiring a massive conversion effort. Once an application is fully converted to Service Locator, it is a trivial step to further convert it to Dependency Injection.
The Service Locator is a static class that is referenced from all parts of the system (this is the part that Service Locator detractors object to). As such, it needs to be located in a central project that can be referenced by all classes that need it. Depending on how your IoC container works, this project may also need to be able to reference the projects where the Interfaces and Classes are kept. If you have a large solution, finding a good place to put the Service Locator can be one of the most difficult parts […]