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.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
  • 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` and `ConcurrentQueue`, or you need to do manual locking in the calling code, typically chaining several method calls inside a single lock. – CodesInChaos Sep 20 '12 at 21:34
  • Do all your methods have same signature? – prashanth Sep 20 '12 at 22:21

2 Answers2

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

Community
  • 1
  • 1
Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
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

TJB
  • 13,367
  • 4
  • 34
  • 46