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!
Echoing the two other; DI is the way to go. Dynamic Proxy is very competent in this respect.
Here is some example code, complete with implementation of all that is required. Normally it’s good practice to code against an interface.
I can recommend reading a bit about AOP, here’s my thread on it:
Help and Information about Aspect Oriented Programming
(Edit: Becuase you were nice and gave me some points, here’s another cool link to a DP tutorial that’s really well done: http://kozmic.pl/archive/2009/04/27/castle-dynamic-proxy-tutorial.aspx ;))
Here is example code:
Console output