Frage

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?

War es hilfreich?

Lösung

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;

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top