Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle Interface Proxy without target

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?

like image 511
rollaeriu360 Avatar asked Mar 27 '26 18:03

rollaeriu360


1 Answers

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;

like image 73
Miguel Gamboa Avatar answered Mar 29 '26 07:03

Miguel Gamboa