I am trying to create a Proxy for an interface without a target and I always get a System.NullReferenceException when I invoke a method on the resulting proxy, although, the interceptor is always well invoked.

Here it is the definition for the interface and the interceptor:

internal class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
            Console.WriteLine(invocation.Method.Name);
    }
}

public interface IMyInterface
{
    int Calc(int x, int y);
    int Calc(int x, int y, int z);
}

And here it is the Main program:

class Program
{
    static void Main(string[] args)
    {
        ProxyGenerator generator = new ProxyGenerator();

        IMyInterface proxy = (IMyInterface) generator.CreateInterfaceProxyWithoutTarget(
            typeof(IMyInterface), new MyInterceptor());

        proxy.Calc(5, 7);
    }
}

The interceptor is invoked but I get an exception from the DynamicProxyGenAssembly2. Why?

有帮助吗?

解决方案

The problem is in the return type of the Calc method that is a primitive Int32. Once you are not specifying the returned value in your interceptor then it will return null and thus, when the proxy tries to convert that value to Int32 it will throw a NullPointerException.

To fix the problem you should set the return value in the interceptmethod, e.g. invocation.ReturnValue = 0;

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top