Search code examples
c#castle-dynamicproxy

Castle Dynamic Proxy how to merge data in CreateClassProxyWithTarget


It is possible to add proxy capabilities to an already generated and not empty object using Castle Dynamic Proxy?

I've tried this:

Dog _myDog=new Dog();
_myDog.Name="Fuffy";

var _proxyDog = generator.CreateClassProxyWithTarget<Dog>(_myDog, ProxyGenerationOptions.Default, new DogInterceptor());

_proxyDog results as a new object.

Now this is only an example, in real world application my object has 30+ properties and I want to know if I can avoid to copy those props one by one!


Solution

  • Yes it is. The only problem: ProxyGenerator needs to instantiate an object of that type anyway. This code is actually working correctly in my project:

    public static class MongoExtensions
    {
        static readonly ProxyGenerator pg = new ProxyGenerator();
        public static MongoCollection GetRetryCollection(this MongoDatabase db, string collectionName, int retryCount = 5, int pauseBetweenRetries = 2000)
        {
            var coll = db.GetCollection(collectionName);
            return (MongoCollection)pg.CreateClassProxyWithTarget(typeof(MongoCollection), coll, new object[] { db, collectionName, coll.Settings }, new RetryingInterceptor { RetryCount = retryCount, PauseBetweenCalls = pauseBetweenRetries });
        }
    }
    

    Paramerts of CreateClassProxyWithTarget are:

    • type of the proxied object,
    • proxied instance
    • array of constructor paramers for the proxied type.
    • interceptor for this proxy.

    I can't really explain, why it need constructor parameters for the object, but this code work correctly for me.