I am trying to come up with a way that (either static or instance) method calls can be intercepted by dynamic proxy. I want to implement it as c# extension methods but stuck on how to generate dynamic proxy for static methods.
Some usages:
Repository.GetAll<T>().CacheForMinutes(10);
Repository.GetAll<T>().LogWhenErrorOccurs();
//or
var repo = new Repository();
repo.GetAll<T>().CacheForMinutes(10);
repo.GetAll<T>().LogWhenErrorOccurs();
I am open to any library (linfu, castle.dynamic proxy 2 or etc).
Thanks!
Totally impossible.
In fact, proxies can't even be generated on all instance methods - they have to be virtual, so that the proxy generator can create a derived class and override them.
Static methods are never virtual, and therefore, cannot be overridden by a proxy.
(Technically there's a workaround for non-virtual methods which is to derive the class from MarshalByRefObject
, but remoting-based solutions to this are slow and clunky and still won't support static methods.)
Given that your class is named Repository
, I'm going to suggest that you make these methods instance methods instead. These kinds of operations generally shouldn't be static
to begin with. If you make them static
, you lose a lot of things: Loose coupling, mocking, dependency injection, a certain amount of unit testability, and - as you've just discovered - proxying and interception.