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 primitiveInt32
. Once you are not specifying the returned value in your interceptor then it will returnnull
and thus, when the proxy tries to convert that value toInt32
it will throw aNullPointerException
.To fix the problem you should set the return value in the
intercept
method, e.g.invocation.ReturnValue = 0;