ObjectFactory 究竟是什么,它的用途是什么?

what exactly ObjectFactory is, and, whats is it used for?

这是我的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 是什么?为什么我找不到关于它的任何名称空间?为什么 iv 得到:

the name ObjectFactory doesnt exist in current context

我尝试了很多使用控制器工厂的方法,当我在代码中感受到对象工厂时,我遇到了这个问题......这真的让我感到厌烦

ObjectFactory 是 StructureMap 容器的静态实例。它已从 StructureMap 中删除,因为在应用程序 composition root (which leads down the dark path to the 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 扩展点,例如 ,但是当您这样做时,请确保所有这些都在组合根内部完成。