Search code examples
c#asp.netdesign-patternsmvp

When using a singleton design pattern, which construction is preferred and why?


Aside from "what is so bad about singletons" :-), I have an ASP.NET web application that utilises singletons at the business logic layer, thus:

public class MyBusinessService
{
    private static MyBusinessService mInstance = null;

    public static MyBusinessService Instance
    {
        get { return mInstance; }
    }

    static MyBusinessService()
    {
        mInstance = new MyBusinessService();
    }
}

We use them primarily for a dependency in a Model View Presenter architecture.

They can also be used across business logic classes in one of two ways. Firstly in the following manner:

var myService = new MyBusinessService();
myService.DoSomething();
myService.DoSomethingElse();

Or, it can be used in the following manner:

MyBusinessService.Instance.DoSomething();
MyBusinessService.Instance.DoSomethingElse();

Which construct is preferred and why? I'm not interested in whether the singleton pattern itself is good or bad.

Update: Ok, this question seems to be quite popular. I guess it is a quasi-singleton. Worst of both worlds! I'm not really interested in refactoring the pattern / anti-pattern / code hell. I'm more interested in understanding the effects of both usages described.

Our view (ASP.NET page) looks like this:

var presenter = new SomeViewPresenter(this, MyBusinessService.Instance);

but could alternatively be implemented as:

var presenter = new SomeViewPresenter(this, new MyBusinessService());

I prefer the former in this case. N.B. The use of the word singleton and the incorrect usage above is understood, but as the code stands, what is the outcome of the two original options?


Solution

  • The latter is preferred because the former isn't behaving like a singleton - you are instantiating a new instance without any guards for stopping more than one instance existing.

    The latter is the code you'd likely end up with if you put these guards in place. You don't need to use the property all the time too:

    var service = MyBusinessService.Instance;
    service.This();
    service.That();
    

    I also look at statics in ASP.NET with some skepticism and this is from a WinForms developer :-)