I am trying to implement AOP logging using castle's dynamic proxy library in a .net MVC 4 application. We are using structure map for our dependency injection.
I have successfully set up AOP logging for our standard normal MVC controllers, but we also have a folder with WebAPI controllers that we also use.
The problem I have is that for any of the WEBApi calls I get the following error
"Unable to cast object of type 'Castle.Proxies.IHttpControllerProxy' to type 'Web.Controllers.Services.Home.apiContollerName'.","ExceptionType":"System.InvalidCastException"
Here are the set details of my interceptor set-up
//Logging Interceptor in strucutremap ObjectFactory.Initialize
x.RegisterInterceptor(new LogTypeInterceptor());
Here is my Process Method
public object Process(object target, IContext context)
{
var obj = new object();
obj = _proxyGenerator.CreateInterfaceProxyWithTargetInterface(
target.GetType().GetInterfaces().First(),
target.GetType().GetInterfaces(),
target, new LoggingInterceptor());
return obj;
}
I suspect I need to call a different method on _proxyGenerator but i'm new to this not sure what method I should call.
The problem seems to be that your proxy class is only mimicking the interfaces and not the base class, so the code falls over when the internal WebAPI code tries to cast the proxy to the controller class. If you replace your call to CreateInterfaceProxyWithTargetInterface with a call to
_proxyGenerator.CreateClassProxyWithTarget(target.GetType(),
target,
new LoggingInterceptor());
then this problem will go away, but a new one will be introduced: the proxy creation will fail for any classes which don't have a parameterless constructor with the error message 'No parameterless constructor defined for this object.' So you may have to add parameterless contructors to all your classes. If you could switch to using Castle Windsor as your IoC then you can use the interceptors and IoC as a one-stop shop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With