Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 96,142 hits
  • Meta

Posts Tagged ‘Singleton Dependency Injection’

The Singleton and Composition/Testability

Posted by coreycoogan on September 3, 2010


I read this post from Kellabyte which got me thinking about solutions I’ve used in the past.  There’s ways to live with Singletons, at least from a composition and testability standpoint.  This can come in especially handy when working with a legacy code base.

The first thing, is that your property/method that returns the instance of the Singleton should return an interface, not a concrete.

public static ILog Instance
{
     get{ return _logger;}
}

I assume when talking about composition, we are all using an IoC container of some kind.  My favorite is StructureMap.  Most containers have the ability to configure a type resolution through a factory method.

In SM, it might look like this:

ForSingletonOf<ILog>()
.Use(() => Logger.Instance)

Now any requests from your container that require an ILog instance can come from the Singleton in production, but resolve to a mock or anything else in test scenarios.

//example of Dependency Injection via constructor
public class SoSomethingService(ISomethingRepository repo, ILog logger)
{
//set to instance vars
}

Posted in C#, Design Patterns, IoC, StructureMap | Tagged: , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.