How to automatically generate Decorator template in C #

I have an interface and a class that implements this interface, for example:

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 will decorate each of the concrete methods of the class with some specific logic that must be executed in a non-working environment before and after the call.

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

My question is: is there an easier way to automatically create such a class, besides using reflection on the interface, and creating a text file with the cs extension?

+6
c # design-patterns decorator
source share
6 answers

Personally, I would simply explicitly register where it was needed, but if you configured it to use a decorator, you can use the class

+8
source share

Have you tried PostSharp ? This can help you automatically โ€œinstrumentalโ€ classes and reach your logging script without creating decorators.

+2
source share
+2
source share

I wrote a T4 template that can create a decorator for fairly complex classes based on some simple conventions. The project can be found on GitHub - T4Decorators . The works are similar to the T4MVC, that's where I got this idea.

+2
source share

Could you use T4 and reflection?

Perhaps these other questions may help:

  • T4 Code Generation: Access Types in the Current Project
  • How do you use .Net reflection with T4
+1
source share

We have the same requirement and wrote the Roslyn generator for this, look here: https://github.com/proactima/ProxyGen You need to slightly modify the code to suit your needs. We basically wrap interface methods (all from a specific namespace) in the "ReliableServiceCall" method. It is trivial to change this to do something else.

+1
source share

All Articles