Understanding the Service Locator pattern – Dependency Injection

Conclusion

This section explored replacing the classic Singleton pattern with a standard instantiable class registered with a singleton lifetime. We looked at the old application state, learned that it was no more, and implemented two versions of it. We no longer need that, but it was a good way of learning about singletons.We then implemented a wishlist system as a second example. We concluded that the whole thing was working due to and managed by a single line of the composition root: the call to the AddSingleton method. Changing that line could drastically change the system’s behavior, making it unusable.From now on, you can see the Singleton pattern as an anti-pattern in .NET, and unless you find strong reasons to implement it, you should stick to normal classes and DI instead. Doing this moves the creation responsibility from the singleton class to the composition root, which is the composition root’s responsibility, leaving the class only one responsibility.Next, we explore the Service Locator anti-pattern/code smell.

Understanding the Service Locator pattern

Service Locator is an anti-pattern that reverts the IoC principle to its Control Freak roots. The only difference is using the IoC container to build the dependency tree instead of the new keyword.There is some use of this pattern in ASP.NET, and we may argue that there are some reasons for using the Service Locator pattern, but it should happen rarely or never in most applications. For that reason, let’s call the Service Locator pattern a code smell instead of an anti-pattern.My strong recommendation is don’t use the Service Locator pattern unless you know you are not creating hidden coupling or have no other option. As a rule of thumb, you want to avoid injecting an IServiceProvider in your application’s codebase. Doing so reverts to the classic flow of control and defeats the purpose of dependency injection.A good use of Service Locator could be to migrate a legacy system that is too big to rewrite. So you could build the new code using DI and update the legacy code using the Service Locator pattern, allowing both systems to live together or migrate one into the other, depending on your goal. Fetching dependencies dynamically is another potential use of the Service Locator pattern; we explore this in Chapter 15, Object Mappers, Aggregate Services, and Façade.Without further ado, let’s jump into some more code.

Leave a Reply

Your email address will not be published. Required fields are marked *



         


          Terms of Use | Accessibility Privacy