使用城堡动态代理与Web Api控制器

问题描述 投票:3回答:1

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

我已成功为我们的标准普通MVC控制器设置AOP日志记录,但我们也有一个带有WebAPI控制器的文件夹,我们也使用它。

我遇到的问题是,对于任何WEB Api调用,我都会收到以下错误

"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个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.