通过扩展DefaultControllerFactory与实现IDependencyResolver来实现DI之间的区别

Ste*_*a D 4 c# asp.net-mvc dependency-injection asp.net-mvc-4

我们可以通过实现IDependencyResolver或扩展DefaultControllerFactory来在MVC中进行DI

我曾经认为这两种不同的方法之间差别不大.

但是,我正在完成我的MVC书,它让我实现了自己的ControllerFactory(而不是扩展默认值),而在CreateController方法中,它实际上有:

(IController) DependencyResolver.Current.GetService(targetType);
Run Code Online (Sandbox Code Playgroud)

所以看起来DefaultControllerFactory实际上使用了DependencyResolver

两者之间必须存在差异,我认为这只会让我感到困惑.

问题

1)本书是否让我使用依赖解析器以简化CustomControllerFactory的实现,而实际的DefaultControllerFactory不使用它?

2)我很难理解这两者的目的.我曾经认为只有两种不同的方式来实现DI,但是我越是深入了解我感觉它们完全不同.看起来依赖性解析器是所有控制器实例化的地方

3)是否有最佳做法试图在两者之间做出选择?也许是一些专业和缺点?

编辑:为清楚起见,我决定上传整个CreateController方法:

  public IController CreateController(RequestContext requestContext, string controllerName)
  {
     Type targetType = null;

     switch (controllerName)
     {
        case "Product":
           targetType = typeof (ProductController);
           break;
        case "Customer":
           targetType = typeof (CustomerController);
           break;
        default:
           requestContext.RouteData.Values["controller"] = "Product";
           targetType = typeof (ProductController);
           break;
     }

     return targetType == null ? null : (IController) DependencyResolver.Current.GetService(targetType);
  }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ann 6

坚持下去DefaultControllerFactory.

IDependencyResolver是Service Locator反模式的一个示例,IMO从未添加到MVC(或Web API,就此而言).虽然许多人混淆了服务位置和依赖注入,但它们是解决与接口编程相关的一些常见问题的两种极其不同的尝试.

但是,当您权衡服务定位器与DI的优缺点时,您会发现Service Locator确实是一种反模式,因为它引入了比它解决的问题更多的问题.虽然它旨在解决一些问题,但它实际上并没有解决DI无法解决的任何问题.