If possible, you should always go with dependency injection, as it has several distinct advantages. However, using user interface technologies, it is not always possible to use dependency injection, because some user interface technologies (for example, in the .NET space, Win Forms and Web Forms) allow only your classes (forms, pages, controls, etc.) default constructor. In this case, you will have to return to something else that is a service locator.
In this case, I can give you the following advice:
- Return to Service Locator for user interface classes that cannot be created by your container using dependency injection, and for things that you do not test in the module.
- Try to implement as little logic as possible in those classes of the user interface (as Humble objects only taking into account the view). This allows the maximum unit test.
- Wrap the container around the static method to hide the container from the rest of the application. Make sure that the call to this static method fails when the dependency cannot be resolved.
- Allow all dependencies in the constructor (by default) of this type. This allows the application to crash quickly when one of its dependencies cannot be resolved when creating this type, and not later when the button is pressed.
- Check at application startup (or using unit test) if all types of user interface can be created. This will save you from having to go through the entire application (by opening all forms) to see if there is an error in the DI configuration.
- When types cannot be created by the container, there is no reason to register them in the container. If they can be created by the container (for example, using the ASP.NET MVC Controller classes), it may be useful to register them explicitly, as some containers allow you to check the configuration from the front, which will detect configuration errors in these types correctly away.
In addition to unit testing, there are two other important arguments in favor of using the service locator, which Mark Semann gives in his famous blog post Service Locator Anti-pattern :
- Service Locator "hides class dependencies, causing runtime errors instead of compile-time errors"
- Service locator "makes code more difficult to maintain"
source share