Alex Rivera | Logout

How to auto generate Decorator pattern in C#

Asked 2010-12-08T08:52:33.157
10

I have some interface, and a class implementing this interface, say:

interface IMyInterface
{
     void Func1();
     void Func2();
}

class Concrete : IMyInterface
{
     public virtual void Func1() { //do something }
     public virtual void Func2() { //do something }
}

Now, I want to create a class that decorates each of the concrete class methods with some specific logic, to be executed in non production environment, before and after the call.

class Decorator : Concrete
{ 
     public override void Func1() { Pre(); base.Func1; Post(); }
     public override void Func2() { Pre(); base.Func2; Post(); }
}

My question is there a simpler way to auto generate such class other than use reflection on the interface and create a text file with cs extension?

Edit
Report

3 Answers

2

Have you tried PostSharp? It can help you automatically "instrument" classes and achieve your logging scenario without actually creating decorators.

answered 2010-12-08T08:58:55.417
2

What about the Logging Application block?

http://msdn.microsoft.com/en-us/library/ff647183.aspx

answered 2010-12-08T09:05:10.567
1

Could you use T4 and reflection?

Maybe these other questions could help:

answered 2010-12-08T08:58:29.800

Your Answer