【问题标题】:Using Castle Dynamic Proxy with WebApi Controllers将 Castle 动态代理与 WebApi 控制器一起使用
【发布时间】:2013-06-21 10:19:37
【问题描述】:

我正在尝试在 .net MVC 4 应用程序中使用 Castle 的动态代理库来实现 AOP 日志记录。我们使用结构映射来进行依赖注入。

我已经成功地为我们的标准普通 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 上调用不同的方法,但我不知道应该调用什么方法。

【问题讨论】:

    标签: .net asp.net-mvc-4 asp.net-web-api castle castle-dynamicproxy


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2013-11-17
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多