Why is MVC4 using the Service Locator Anti-Pattern?

前端 未结 2 603
夕颜
夕颜 2020-12-23 11:43

After reading \"Dependency Injection in .NET\" by Mark Seemann I stay away from the Service Locator which is an anti-pattern.

Upon reading the release notes on MVC

2条回答
  •  醉梦人生
    2020-12-23 12:07

    As Darin points out, ASP.NET MVC 4 is a Framework and is container agnostic. That's why it provides a service locator in the form of IDependencyResolver. This allows anyone to plug in their container of choice.

    However, I wouldn't call this an anti pattern. This allows you to use the container of your choice, but it doesn't force you the application developer to use service location. If the framework forced the developer to use Service Location, then I would call it an anti-pattern. But the developer who builds an ASP.NET MVC application is free to use DI via constructor injection, property setup, or service location. It's their choice.

    Look at all the ASP.NET MVC examples of dependency injection published by me or the ASP.NET MVC team. In pretty much all cases, they're using constructor injection. They're not using service location.

    In fact, most of the ASP.NET MVC source code itself doesn't use service location to retrieve dependencies. There's a few key places where the MVC calls into the service locator for legacy APIs and such. But that's about it.

提交回复
热议问题