0

这是我的StructureMapControllerFactory,我想用它在mvc5项目究竟是什么ObjectFactory是什么,它用于什么?

public class StructureMapControllerFactory : DefaultControllerFactory 
{ 
    private readonly StructureMap.IContainer _container; 

    public StructureMapControllerFactory(StructureMap.IContainer container) 
    { 
     _container = container; 
    } 

    protected override IController GetControllerInstance(
     RequestContext requestContext, Type controllerType) 
    { 
     if (controllerType == null) 
      return null; 

     return (IController)_container.GetInstance(controllerType); 
    } 
} 

我配置我的控制器厂在global.asax这样的:

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 

     var controllerFactory = new StructureMapControllerFactory(ObjectFactory.Container); 

     ControllerBuilder.Current.SetControllerFactory(controllerFactory); 
     AreaRegistration.RegisterAllAreas(); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
    } 
} 

,但什么是ObjectFactory?为什么我无法找到关于这个的任何名称空间?为什么四有:

名称的ObjectFactory犯规在目前情况下存在

我尝试使用控制器工厂的许多方法和IV得到了这个问题,当我在代码中感觉到对象工厂......它真的很无聊我的

回答

1

ObjectFactory是StructureMap容器​​的静态实例。它已从StructureMap中删除,因为在应用程序的composition root(它导致黑暗路径导致service locator anti-pattern)的任何地方访问容器不是一个好习惯。

因此,为了保持DI友好的一切,您应该传递DI容器实例,而不是使用静态方法。

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     // Begin composition root 

     IContainer container = new Container() 

     container.For<ISomething>().Use<Something>(); 
     // other registration here... 

     var controllerFactory = new StructureMapControllerFactory(container); 

     ControllerBuilder.Current.SetControllerFactory(controllerFactory); 
     AreaRegistration.RegisterAllAreas(); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 

     // End composition root (never access the container instance after this point) 
    } 
} 

您可能需要容器注入其他MVC扩展点,如global filter provider,但是当你确保所有这一切都构成根的内部完成。