Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for storing a singleton instance in ASP.NET application

If we have a singleton class like LoadBalancer and need one instance per ASP.NET application, then where to store it ?

Currently I use Application.Add("LoadBalancer", LoadBalancer.Instance) in Application_Start() in Global.asax.

Also Application object is created by ASP.NET and there are multiple instances per application based on workload. Also I can declare a static instance of my LoadBalancer in Global.asax.

Which is preferred ? Any better idea ?

like image 370
Xaqron Avatar asked Dec 30 '10 17:12

Xaqron


3 Answers

If it is a Singleton why do you want to store in Application items? Isn't it supposed to return the same instance when you use LoadBalancer.Instance from anywhere in the application?

In case your site is using load balancing or is ina web farm each server would have its instance of Application object and LoadBalancer.Instance.

like image 76
Chandu Avatar answered Nov 05 '22 07:11

Chandu


You dont have to store a singleton object in Application object. Standard implementation of Singleton object holds good. http://msdn.microsoft.com/en-us/library/ff650316.aspx

But if you using a Web Farm its a different story, you should have the Singleton object hosted seperately on a different service and all the servers should request the object from that service using Remoting or WCF.

like image 31
XtremeBytes Avatar answered Nov 05 '22 06:11

XtremeBytes


Use an IOC container like Castle Windsor. The default lifestyle in Castle Windsor is singleton.

http://www.castleproject.org/container/documentation/v21/usersguide/lifestyles.html

like image 39
Bobby Richard Avatar answered Nov 05 '22 06:11

Bobby Richard