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,但是當你確保所有這一切都構成根的內部完成。