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?