Search code examples
c#proxy-classes

Define the base class or base functionality of a dynamic proxy (e.g. Castle, LinFu)


I've asked this in the NHibernate forumns but I think this is more of a general question. NHibernate uses proxy generators (e.g. Castle) to create its proxy.

What I'd like to do is to extend the proxy generated so that it implements some of my own custom behaviour (i.e. a comparer). I need this because the following standard .NET behaviour fails to produce the correct results:

//object AC is a concrete class
collection.Contains(AC) = true

//object AP is a proxy with the SAME id and therefore represents the same instance as concrete AC
collection.Contains(AP) = false

If my comparer was implemented by AP (i.e. do id's match) then collection.Contains(AP) would return true, as I'd expect if proxies were implicit. (NB: For those who say NH inherits from your base class, then yes it does, but NH can also inherit from an interface - which is what we're doing)

I'm not at all sure this is possible or where to start. Is this something that can be done in any of the common proxy generators that NH uses?


Solution

  • This kind of behavior is possible with LinFu.DynamicProxy, but you would have to replace the interceptor provided by NHibernate with your own custom interceptor that delegates it calls back to the original interceptor:

    var yourProxiedInterfaceInstance = ...
    
    // Get the Interceptor that NHibernate uses
    
    var proxy = (IProxy)yourProxiedInterfaceInstance;
    
    var interceptor = proxy.Interceptor;
    
    // You'll need to create a decorator class around the IInterceptor interface
    var yourInterceptor = new SomeCustomInterceptor(interceptor); 
    
    // Replace the interceptor here
    proxy.Interceptor = yourInterceptor;
    

    This is pretty easy to do with LinFu since every proxy instance that it generates requires an interceptor. If you change the interceptor, then you can automatically change a proxy's behavior. I hope that helps.