I need to use Castle DynamicProxy to proxy an interface by providing an instance of it to ProxyGenerator.CreateInterfaceProxyWithTarget. I also need to make sure that calls to Equals, GetHashCode and ToString hits the methods on the concrete instance, that I am passing, and I can’t get that to work.
In other words, I’d like this small sample to print True twice, while in fact it prints True,False:
using System;
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
public interface IDummy
{
string Name { get; set; }
}
class Dummy : IDummy
{
public string Name { get; set; }
public bool Equals(IDummy other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Name, Name);
}
public override bool Equals(object obj)
{
return Equals(obj as IDummy);
}
}
class Program
{
static void Main(string[] args)
{
var g = new ProxyGenerator();
IDummy first = new Dummy() {Name = "Name"};
IDummy second = new Dummy() {Name = "Name"};
IDummy firstProxy = g.CreateInterfaceProxyWithTarget(first, new ConsoleLoggerInterceptor());
IDummy secondProxy = g.CreateInterfaceProxyWithTarget(second, new ConsoleLoggerInterceptor());
Console.WriteLine(first.Equals(second));
Console.WriteLine(firstProxy.Equals(secondProxy));
}
}
internal class ConsoleLoggerInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Invoked " + invocation.Method.Name);
}
}
Is this possible with DynamicProxy ? How ?
This is a bit tricky. Take a look at documentation on how proxies work. Interface proxies wrap an object and intercept calls to designated interface(s). Since
Equalsis not part of that interface the second call to equals is comparing proxies, not their targets.So what provides the implementation for the second
Equalscall?Proxy is just another class implementing your
IDummyinterface. As any class it also has a base class, and that’s the base implementation ofEqualsthat gets invoked. This base class is by defaultSystem.ObjectI hope you see now where this is going. Solution to this problem is to tell proxy to implement some proxy aware base class that will forward the calls to proxy target. Part of its implementation might look like this:
Now you only need to instruct the proxy generator to use this base class for your interface proxies, instead of the default.