1

I'm using this post to create authorization in my MVC4 project. The problem is that I'm using Castle Windsor as DI. When invoking the function below I get an error on the line 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
}

The error I get is:

Unable to cast object of type 
'Castle.Proxies.IControllerProxy_2' to type 'System.Web.Mvc.ControllerBase'.

Is there a way so I can make this work?

Community
  • 1
  • 1
Thijs
  • 3,015
  • 4
  • 29
  • 54
  • Could you post your ControllerFactory and your controller registration code? On the face of it your code should work because the proxy should derive from the controller class, which should derive from the ControllerBase class. – Polly Shaw Aug 02 '14 at 19:49

1 Answers1

1

The fact that you get an Castle.Proxies.IControllerProxy_2 has to do that you have added an interceptor to your component. When you register your component, register the component itself as service as well instead of only the interface. This will for windsor to create a class proxy. ie instead of:

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

use

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

In case you are registering using Types, add WithServiceSelf.

Kind regards, Marwijn.

Marwijn
  • 1,681
  • 15
  • 24