Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto generate Decorator pattern in C#

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?

like image 239
Amittai Shapira Avatar asked Dec 08 '10 08:12

Amittai Shapira


2 Answers

Personally I would just explicitly log where needed, but if you are set on using a decorator to do this you could use the RealProxy class.

It could look something like this:

public class DecoratorProxy<T> : RealProxy
{
    private T m_instance;

    public static T CreateDecorator<T>(T instance)
    {
        var proxy = new DecoratorProxy<T>(instance);
        (T)proxy.GetTransparentProxy();
    }

    private DecoratorProxy(T instance) : base(typeof(T))
    {
        m_instance = instance;

    }
    public override IMessage Invoke(IMessage msg)
    {
        IMethodCallMessage methodMessage = msg as IMethodCallMessage;
        if (methodMessage != null)
        {
            // log method information

            //call method
            methodMessage.MethodBase.Invoke(m_instance, methodMessage.Args);
            return new ReturnMessage(retval, etc,etc);

        }

    }
}
like image 182
SpeksETC Avatar answered Oct 10 '22 10:10

SpeksETC


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

like image 26
Alex Shtof Avatar answered Oct 10 '22 09:10

Alex Shtof