Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking for a way to automatically generate (e.g.) singleton, like:

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

as an attempt to eliminate boilerplate.

Does somebody know how it can be accomplished ? I know there are CodeDOM, Reflection.Emit, T4 and so on. Also - there is (most notably) PostSharp, but I'd be really glad to see a real solution for the above challenge.

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

Edit:

The issue here is not the Singleton, but the generative / meta programming in C# - how to create code / eliminate boiler-plate in the best way - what kind of concrete examples there are ?

like image 733
Tar Avatar asked Oct 22 '22 14:10

Tar


1 Answers

I do this exact thing for my logging class, using an IOC container and adding the scope when mapping/binding the object. For instance using Ninject, the binding would be:

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

Then in my classes where I want to use my singleton logger, I can use property injection:

[Inject]
public ILogger Logger { get; set; }
like image 116
Adrian Thompson Phillips Avatar answered Oct 29 '22 04:10

Adrian Thompson Phillips