Circumventing statics and singletons

November 20th, 2007

One thing that I find spoils a design is the use (or overuse) of statics and singletons. Right now I’m writing a ViewComponent to render site maps. I’m leveraging the site map providers that ASP.Net supports. At some point my ViewComponent needs to use the default provider or fetch a named one. Here’s the code:

public class SiteMapViewComponent : ViewComponent
{
    ...

    public override void Initialize()
    {
        targetProvider = SiteMap.Provider;

        base.Initialize();
    }

...

While that works, it demonstrates how your code might get coupled with the default ASP.Net implementation, not to mention that it would be tricky to implement an unit test for the view component without messing the appdomain configuration and the providers API.

My usual solution to these cases is to create accessors that can be replaced. So my view component will have, by default, an ASP.Net provider accessor instance. My test case can replace the default accessor by a mocked one.

public class SiteMapViewComponent : ViewComponent
{
    private SiteMapProvider targetProvider;

    private string providerName;
    private string customView;
    private IProviderAccessor providerAccessor = new AspNetProviderAccessor();

    // Public Property so tests and others can customize the accessor 
    public IProviderAccessor ProviderAccessor
    {
        get { return providerAccessor; }
        set { providerAccessor = value; }
    }

    ...

    public override void Initialize()
    {
        targetProvider = providerAccessor.DefaultProvider;

        base.Initialize();
    }

    ...
}

public interface IProviderAccessor
{
    SiteMapProvider DefaultProvider { get; }

    SiteMapProvider this[string providerName] { get; }
}

public class AspNetProviderAccessor : IProviderAccessor
{
	public SiteMapProvider DefaultProvider
	{
		get { return SiteMap.Provider; }
	}

	public SiteMapProvider this[string providerName]
	{
		get { return SiteMap.Providers[providerName]; }
	}
}

Much more elegant!

One Response to “Circumventing statics and singletons”

Darius Damalakas Says:

I do the same technique. Not the worst one, but i feel that is not the most elegant one.. though i can not explain why. just the feeling :)

Leave a Reply