Corey Coogan

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

  • Subscribe

  • Archives

  • Blog Stats

    • 71,265 hits
  • Meta

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
}
About these ads

One Response to “The Singleton and Composition/Testability”

  1. kellabyte said

    Kelly here, so happy that my blog post inspired your blog post :) Good example too!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: