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 ?