这是我的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名称在当前上下文中不存在
我尝试了很多使用控制器工厂的方法,当我觉得代码工厂在代码中时,我遇到了这个问题...它真的很无聊我的
答案 0 :(得分: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,但是当您确保所有这些都在组合根目录内完成时。