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 that you use 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 code base. Doing so reverts to the classic flow of control and defeats the purpose of DI.
A good use of Service Locator could be to migrate a legacy system that is too big to rewrite. So, you...