How to automatically create (e.g. singleton with C # using CodeDOM / T4 / PostSharp / whatever?

I am looking for a way to automatically create (e.g.) singleton, for example:

[SingletonPatternAttribute]
public class Logger {
    public void Log (string txt) { /* do logging... */ }
}

as an attempt to eliminate the template.

Does anyone know how to do this? I know that there are CodeDOM, Reflection.Emit, T4and so on. Also - there is (most noticeably) PostSharp, but I would be very glad to see a real solution for the aforementioned task.

I can do code generation in the constructor, for example, but the compilation time is obviously much better.

Edit:

The problem here is not singleton, but in generator / meta programming in C#- how to create code / exclude the boiler stove in the best way - what specific examples are there?

+5
2

, IOC / . , Ninject, :

Bind<ILogger>().To<Logger>().InSingletonScope();

, , :

[Inject]
public ILogger Logger { get; set; }
+2

, , , . , , , , , .

"" :

  • Reflection.Emit
  • T4
  • CodeDom ( , , !)

:

  • IL API- Profiler ( )
  • ContextBoundObject ( )
  • # (Roslyn/MonoCSharp) , scriptcs ( , )

, , "" AOP, - OP: "special", . AOP # ( , , ), PostSharp. , , : ( ). Reflection.Emit IL- API- Profiler .

, T4, ; (, ), (!) .

Reflection.Emit

: ( MakeProxy) , dll ( "" ), , .

, .NET, MS Build .

: . DLL, , ... . , "" ( IDE) , ; .

API-

, Reflection.Emit, - ""; IL (.. , ). () DLL- . "" , (, , JITed), .

: "" (, ,...) ( ); IL API ( , , - , - !) : ( - , ).

T4

T4 , . , : "" ( ... ).

: IDE ; intellisense; ; ,

( ) T4, # → #; , IDE ( intellisense "", "" ) Reflection.Emit. , #/#, VS-, .

: "", Reflection.Emit, , IKVM emit, Sigil

+1

All Articles