2014-07-24 34 views
1

我使用this post在我的MVC4項目中創建授權。問題是我使用Castle Windsor作爲DI。當調用該函數下面我就行了return (ControllerBase) controllerCast Castle IControllerProxy到ControllerBase

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'. 

有沒有一種方法,所以我可以使這項工作?

+0

你可以發佈你的ControllerFactory和你的控制器註冊碼嗎?在它的表面上,你的代碼應該可以工作,因爲代理應該從控制器類派生,控制器派生自ControllerBase類。 –

回答

1

事實上,你得到一個Castle.Proxies.IControllerProxy_2必須這樣做,你已經爲你的組件添加了一個攔截器。註冊組件時,將組件本身註冊爲服務,而不是隻註冊界面。這將爲windsor創建一個類代理。 即代替:

Component.For<IService>().ImplementedBy<Component> 

使用

Component.For<IService, Component>().ImplementedBy<Component> 

如果您正在使用類型註冊,添加WithServiceSelf。

親切的問候, Marwijn。