3

我试图在.net MVC 4应用程序中使用castle的动态代理库实现AOP日志记录。我们使用结构映射来进行依赖注入。与WebApi控制器一起使用Castle动态代理服务器

我已经成功地为我们的标准正常MVC控制器设置了AOP日志记录,但是我们也有一个WebAPI控制器的文件夹,我们也使用它。

我的问题是,对于任何的WebAPI调用我收到以下错误

"Unable to cast object of type 'Castle.Proxies.IHttpControllerProxy' to type 'Web.Controllers.Services.Home.apiContollerName'.","ExceptionType":"System.InvalidCastException" 

下面是建立我的拦截器的设定细节

//Logging Interceptor in strucutremap ObjectFactory.Initialize 
x.RegisterInterceptor(new LogTypeInterceptor()); 

这里是我的过程方法

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; 

    } 

我怀疑我需要在_proxyGenerator上调用不同的方法,但我是新的这不知道我应该调用什么方法。

回答

1

问题似乎是您的代理类只模仿接口而不是基类,因此当内部WebAPI代码试图将代理强制转换为控制器类时,代码就会失效。如果你有一个调用替换您的来电CreateInterfaceProxyWithTargetInterface

_proxyGenerator.CreateClassProxyWithTarget(target.GetType(), 
    target, 
    new LoggingInterceptor()); 

那么这个问题就会消失,但新将推出:代理创建将用于不具有参数的构造函数的类会失败错误消息'为此对象定义的无参数构造函数。'所以你可能需要添加无参数的构造函数给你的所有类。如果您可以切换到使用Castle Windsor作为您的IoC,然后you can use the interceptors and IoC as a one-stop shop

相关问题