Model view controller ObjectFactory到底是什么?它的用途是什么?

Model view controller ObjectFactory到底是什么?它的用途是什么?,model-view-controller,dependency-injection,structuremap,controller-factory,Model View Controller,Dependency Injection,Structuremap,Controller Factory,这是我的StructureMapControllerFactory,我想在mvc5项目中使用它 public class StructureMapControllerFactory : DefaultControllerFactory { private readonly StructureMap.IContainer _container; public StructureMapControllerFactory(StructureMap.IContainer contain

这是我的
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名称


我尝试了许多使用controller factory的方法,当我感觉代码中的对象工厂时,iv遇到了这个问题……它真的让我厌烦了,我的对象工厂是StructureMap容器的静态实例。它已从StructureMap中删除,因为除了在应用程序中访问容器之外,在任何地方访问容器都不是一个好的做法(这会导致进入应用程序的黑暗路径)

因此,为了使一切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)
    }
}
公共类MVCAPApplication:System.Web.HttpApplication
{
受保护的无效应用程序\u Start()
{
//从根开始合成
IContainer容器=新容器()
container.For().Use();
//其他注册在这里。。。
var controllerFactory=新结构MapControllerfactory(容器);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
//结束合成根目录(在此点之后永远不要访问容器实例)
}
}
您可能需要将容器注入到其他MVC扩展点中,例如a,但是当您确定所有这些都在组合根中完成时