Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Sunday, 25 March 2012

Dependency Injection for Singletons

[Level T2]

This is more of a hypothetical and perhaps philosophical question, but anyway I will shoot:
Now that most DI frameworks support singleton lifetime would you still manually implement the Singleton pattern?
I have seen a lot people answering NO to the question. They believe that the decision to use a singleton pattern can change and changing the lifetime of the object is just change in one line of code or configuration.

But I would answer YES.

Reality is, the reason to use Singleton pattern is usually:

  • Creating the object is expensive
  • Object uses (and commonly caches) data that are expensive to create
  • Object has to collect and keep some state/statistics
Which of above is likely to change over time? I would say practically none. When relying on DI frameworks to do the singleton pattern for you, your class loses its design coherency when it does not communicate its need to be implemented as singleton.


So I personally would implement the Singleton pattern and then register the instance (this is Windsor):

UniversalContainer.Container.Register(
    Component.For<IXsltTransformer>()
    .Instance(XsltTransformerWithCaching.Current)); // .Current is the singleton instance 

As it can be seen, the class XsltTransformerWithCaching is responsible for performing XSLT or XML documents. As we all know, XSLT processor in C# spits out the code for the transformation and builds an assembly at runtime (similar to Serialisation) and if done over and over again, it can cause "memory leaks". As we all know, once an assembly is loaded, it cannot be unloaded - and do not ask for it, it cannot be done.

So I would prefer to bake the singleton into the class.