4

I want to ability to take a class (written and maintained by a third party), wrap it with some magic C# sugar, that lets me wrap each member function (or more) with a custom locking mechanism (or logging mechanism or whatever).

For example,

 class Foo { // someone else wrote this and I can't touch it.
     void A() {}
     void B() {}
     // plus 10,000 other functions I don't want to know about
 }

 class WrappedFoo : Foo { // this is my class, I can do what ever I want
      // this is pseudo code !!
     OnMemberInvoke(stuff) {
        lock {
            Console.WriteLine("I'm calling " + stuff);
            MemberInvoke(stuff);
            Console.Writeline("I'm done calling " + stuff);
        }
     }
     // I could also deal with OnMemberInvokeStart() and OnMemberInvokeDone()
     // pairwise hooks too.
 }

 WrappedFoo wfoo = new WrappedFoo();
 wfoo.A();
 wfoo.B();

output

 I'm calling A
 I'm done calling A
 I'm calling B
 I'm done calling B

Now I think I can do this with DynamicObjects and the TryInvokeMember, but then I lose all the type checking and tab completion I love about C#. In this example, I mentioned lock for thread safety, but I'm looking for a general way of doing this. This code is intended for real-world hardware testing, that needs extra layers of retries, logging, etc.

2
  • Just wrapping each function into a lock is rarely enough to write threadsafe code, so IMO your whole approach is likely flawed. Typically you need to either design the API from ground up with thread safety in mind (see the differences between Queue<T> and ConcurrentQueue<T>, or you need to do manual locking in the calling code, typically chaining several method calls inside a single lock. Sep 20, 2012 at 21:34
  • Do all your methods have same signature?
    – prashanth
    Sep 20, 2012 at 22:21

2 Answers 2

2

I found an answer already on SO.

How to wrap each function in project?

The buzzword is AOP (Aspect Oriented Programming).

It's not built into Visual Studio. There's PostSharp and AspectDNG:

http://www.sharpcrafters.com/postsharp/features

http://aspectdng.tigris.org/nonav/doc/index.html

2

You may want to investigate Aspect Oriented Programming.

PostSharp is a very popular framework that can inject the code before / after method calls, such as threading code, here is an example on Locking.
That could also help with logging, here's an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.