Service Locator is not an Anti-Pattern

submited by
Style Pass
2022-01-12 19:00:29

I often get pushback on MediatR for using service location for resolving handlers, often getting pointed at Mark Seemann's post that Service Locator is an Anti-Pattern. And for all of the examples in the post, I agree that service location in those cases should not be used.

However, like any pattern, it's not so cut and dry. Patterns have advantages and disadvantages, situations where it's advantageous or even necessary to use them, and situations where it's not. In Mark's post, I see only situations that service location is not required and better alternatives exist. However, if you're building anything on .NET Core/6 these days, it's nearly impossible to avoid service location because many of the underlying infrastructure components use it or only expose interfaces that only allow for service location. Why is that the case? Let's examine the scenarios involved to see when service location is required or even preferable.

Modern dependency injection containers have a concept of service lifetimes. Different containers have different lifetimes they support, but in general I see three:

Leave a Comment