我使用这篇文章在我的MVC4项目中创建授权。问题是我使用温莎城堡作为DI。当调用下面的函数时,我在return (ControllerBase) controller
static ControllerBase GetControllerByName(
HtmlHelper helper, string controllerName)
{
IControllerFactory factory =
ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(
helper.ViewContext.RequestContext, controllerName);
if (controller == null)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentUICulture,
"Controller factory {0} controller {1} returned null",
factory.GetType(),
controllerName));
}
return (ControllerBase) controller; // <= error here
}
我得到的错误是:
Unable to cast object of type
'Castle.Proxies.IControllerProxy_2' to type 'System.Web.Mvc.ControllerBase'.
有什么方法可以让我做这件事吗?
您获得Castle.Proxies的事实。IControllerProxy_2必须这样做,你已经添加了一个拦截器到你的组件。当您注册组件时,将组件本身也注册为服务,而不仅仅是接口。这将为windsor创建一个类代理。而不是:
Component.For<IService>().ImplementedBy<Component>
使用Component.For<IService, Component>().ImplementedBy<Component>
如果你注册使用类型,添加withservicesself。
亲切的问候,Marwijn .