Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would you consider this a singleton/singleton pattern?

Imagine in the Global.asax.cs file I had an instance class as a private field. Let's say like this:

private MyClass _myClass = new MyClass();

And I had a static method on Global called GetMyClass() that gets the current HttpApplication and returns that instance.

public static MyClass GetMyClass()
{
    return ((Global)HttpContext.Current.ApplicationInstance)._myClass;
}

So I could get the instance on the current requests httpapplication by calling Global.GetMyClass().

Keep in mind that there is more than one (Global) HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real singleton. But it does follow the pattern to a degree.

So as the question asked, would you consider this at the very least the singleton pattern?

Would you say it should not be used? Would you discourage its use? Would you say it's a possibly bad practice like a true singleton.

Could you see any problems that may arise from this type of usage scenario?

Or would you say it's not a true singleton, so it's OK, and not bad practice. Would you recommend this as a semi-quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give?

Have you ever used anything such as this?

I have used this on past projects, but I am unsure if it's a practice I should stay away from. I have never had any issues in the past though.

Please give me your thoughts and opinions on this.

I am not asking what a singleton is. And I consider a singleton bad practice when used improperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave.

like image 542
mattlant Avatar asked Jan 20 '26 02:01

mattlant


1 Answers

Whether or not this fits the cookie-cutter pattern of a Singleton, it still suffers from the same problems as Singleton:

  • It is a static, concrete reference and cannot be substituted for separate behavior or stubbed/mocked during a test
  • You cannot subclass this and preserve this behavior, so it's quite easy to circumvent the singleton nature of this example
like image 99
Ben Scheirman Avatar answered Jan 22 '26 16:01

Ben Scheirman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!