0

这是我的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得到:

当前上下文中不存在名称 ObjectFactory

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

4

1 回答 1

1

ObjectFactory是 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)
    }
}

您可能需要将容器注入其他 MVC 扩展点,例如全局过滤器提供程序,但当您这样做时,请确保所有这些都在组合根内部完成。

于 2017-03-01T00:06:22.497 回答