Castle DynamicProxy - 'classToProxy'必须是一个类。

3

我可能错过了非常简单的东西。

我只是尝试编写一个非常简约的DynamicProxy使用示例 - 我基本上想拦截调用并显示方法名称和参数值。我的代码如下:

public class FirstKindInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("First kind interceptor before {0} call with parameter {1} ", invocation.Method.Name, invocation.Arguments[0]);
        invocation.Proceed();
        Console.WriteLine("First kind interceptor after the call");
    }
}

public interface IFancyService
{
    string GetResponse(string request);
}

public class FancyService : IFancyService
{
    public string GetResponse(string request)
    {
        return "Did you just say '" + request + "'?";
    }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new FancyService();
        var interceptor = new FirstKindInterceptor();
        var generator = new ProxyGenerator();
        var proxy = generator.CreateClassProxyWithTarget<IFancyService>(service, new IInterceptor[] { interceptor } );

        Console.WriteLine(proxy.GetResponse("what?"));
    }
}

然而, 当我运行它时,我得到以下异常:

未经处理的异常: System.ArgumentException: “classToProxy”必须是一个类 参数名: classToProxy

我错过了什么吗?


1
如果错误出现在 var proxy = generator.CreateClassProxyWithTarget<IFancyService>(service, new IInterceptor[] {interceptor}); 这一行,则你所引用的接口中至少有一个需要引用一个类。 - Dale M
1个回答

6
错误在于 CreateClassProxyWithTarget 需要是一个类而不是接口。CreateInterfaceProxyWithTarget 使用的是接口。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接