【问题标题】:what exactly ObjectFactory is, and, whats is it used for?ObjectFactory 到底是什么,它的用途是什么?
【发布时间】:2017-02-28 12:58:43
【问题描述】:

这是我的StructureMapControllerFactory,我想在 mvc5 项目中使用它

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 在当前上下文中不存在

我尝试了很多使用控制器工厂的方法,当我觉得代码中的对象工厂时,我遇到了这个问题......这真的让我很无聊

【问题讨论】:

    标签: model-view-controller dependency-injection structuremap controller-factory


    【解决方案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,但当您这样做时,请确保所有这些都在组合根内部完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-27
      • 2011-12-17
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多