为什么MVC4使用服务定位器反模式? [英] Why is MVC4 using the Service Locator Anti-Pattern?

查看:129
本文介绍了为什么MVC4使用服务定位器反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读依赖注入在.NET由马克·塞曼我远离服务定位器,这是一种反模式。



阅读发布关于MVC 4的注释我看到:


通过DependencyResolver改进了控制反转(IoC):Web API
使用由MVC依赖
解析器实现的服务定位器模式来获取许多不同设施的实例。


因此我离开好奇和困惑为什么微软将在2012年使用服务定位器。

解决方案

这是一个不应该关心的实现细节。重要的是,现在Web API使用DependencyResolver来解决许多不同工具的依赖关系,只要您想插入这些工具,就可以使用真正的依赖注入。所以在你的代码中,你将使用一个真正的依赖注入。如果Microsoft没有使用 DependencyResolver ,那么在你的代码中必须使用它(作为服务定位器反模式)才能解决依赖关系你想实现一些自定义功能。这对你来说是不好的。现在,对于微软而言,这对于不好,但是你不在乎他们。


所以我好奇了困惑为什么微软将在2012年使用服务定位器。


由于设计框架与使用框架设计应用程序不同。在设计可重用框架(如ASP.NET MVC)时,需要考虑一些不同的事情,而不仅仅是书中的内容。一个例子是设计框架,使得使用这个框架的人能够利用他的代码中使用这个框架在书中写的最佳实践。


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 4 I see:

Improved Inversion of Control (IoC) via DependencyResolver: Web API now uses the service locator pattern implemented by MVC’s dependency resolver to obtain instances for many different facilities.

Thus I'm left curious and confused why Microsoft would use a service locator in 2012.

解决方案

That's an implementation detail that you shouldn't care about. The important thing is that now that the Web API uses the DependencyResolver to resolve dependencies for many different facilities, you will be able to use a real dependency injection whenever you want to plug into those facilities. So in your code you will be using a real dependency injection. If Microsoft didn't use the DependencyResolver then it would have been you that must have used it (as a service locator anti-pattern) in your code in order to resolve dependencies when you want to implement some custom functionality. This would have been bad for you. Now it's bad for Microsoft but you don't care about them.

Thus I'm left curious and confused why Microsoft would use a service locator in 2012.

Because designing a framework is not the same as designing an application using a framework. There are some different things to take into consideration when designing a reusable framework such as ASP.NET MVC rather than just what's written in the books. Some example is to design the framework in such a way that a person using this framework will be able to take advantage of the best practices written in the books in his code using this framework.

这篇关于为什么MVC4使用服务定位器反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆