How to proxy calls to the instance of an object

Posted by mr.b on Stack Overflow See other posts from Stack Overflow or by mr.b
Published on 2010-06-05T14:28:58Z Indexed on 2010/06/05 14:52 UTC
Read the original article Hit count: 164

Edit: Changed question title from "Does C# allow method overloading, PHP style (__call)?" - figured out it doesn't have much to do with actual question. Also edited question text.

What I want to accomplish is to proxy calls to a an instance of an object methods, so I could log calls to any of its methods.

Right now, I have code similar to this:

class ProxyClass {
    static logger;
    public AnotherClass inner { get; private set; }
    public ProxyClass() { inner = new AnotherClass(); }
}

class AnotherClass {
    public void A() {}
    public void B() {}
    public void C() {}
    // ...
}

// meanwhile, in happyCodeLandia...
ProxyClass pc = new ProxyClass();
pc.inner.A(); // need to write log message like "method A called"
pc.inner.B(); // need to write log message like "method B called"
// ...

So, how can I proxy calls to an object instance in extensible way? Method overloading would be most obvious solution (if it was supported in PHP way). By extensible, meaning that I don't have to modify ProxyClass whenever AnotherClass changes.

In my case, AnotherClass can have any number of methods, so it wouldn't be appropriate to overload or wrap all methods to add logging.

I am aware that this might not be the best approach for this kind of problem, so if anyone has idea what approach to use, shoot.

Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about design-patterns