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.
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 ?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With