Castle DynamicProxy : How to Proxy Equals when proxying an interface?

末鹿安然 提交于 2019-11-30 09:03:40

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 Equals is not part of that interface the second call to equals is comparing proxies, not their targets.

So what provides the implementation for the second Equals call?

Proxy is just another class implementing your IDummy interface. As any class it also has a base class, and that's the base implementation of Equals that gets invoked. This base class is by default System.Object

I 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:

public class ProxyBase
{
    public override bool Equals(object obj)
    {
        var proxy = this as IProxyTargetAccessor;
        if (proxy == null)
        {
            return base.Equals(obj);
        }
        var target = proxy.DynProxyGetTarget();
        if (target == null)
        {
            return base.Equals(obj);
        }
        return target.Equals(obj);
    }
    // same for GetHashCode
}

Now you only need to instruct the proxy generator to use this base class for your interface proxies, instead of the default.

var o = new ProxyGenerationOptions();
o.BaseTypeForInterfaceProxy = typeof(ProxyBase);
IDummy firstProxy = g.CreateInterfaceProxyWithTarget(first, o);
IDummy secondProxy = g.CreateInterfaceProxyWithTarget(second, o);

In your sample; your class Dummy implements IDummy, but also provides a more specific override of Equals. An alternative to Krzysztof's suggestion is to pull this method into your interface by having it implement IEquatable<T>, for example:

public interface IDummy : IEquatable<IDummy>
{
    string Name { get; set; }
}

That way, your interface now includes the more specific Equals override, which means your generated proxy will proxy calls to your target as required.

Obviously this doesn't solve the entire problem and will only allow your proxy to forward calls to Equals(IDummy) and not Equals(object) (or GetHashCode for that matter).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!