Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
ASP Insider

Microsoft Store

Using a Singleton In an ASP.NET Application

This was just a bad idea to write, please ignore this post. I was tire, I was in a bad mood and my mind was no where near where it should have been to write this. This was one of those bad ideas that I thought up while driving home from a whirlwind trip to Atlanta. So please never ever reference this post again. :)

Recently I was asked how to use a Singleton in an ASP.NET application. To be more specific I was asked how would I use a singleton and make sure it was applied at the application level. If you have no idea what a Singleton is I will give you my simple definition. It is a pattern used to ensure that an object is only instantiated once. The classic example I offer is ensuring you only have one instance of a desktop application running.

I honestly was not sure about what I would do at the time, I felt I knew, but I was not sure about my thoughts. I was correct in what I was thinking at the time, but it was one of those moments where I just could not think of object names, etc. So it bothered me and as soon as I could get back to my laptop I did a quick and dirty example of what I was thinking.

Now I am not going to get into the details of how to implement a class as a singleton, there are lots of examples all over the web. What want to do is show how you might apply the principle at the application level of an ASP.NET application. In this example I will just store a the current time when an application in first kicked off. I will use a quasi formal singleton, meaning it is a property pattern I commonly use to create one instance of a value.

What I decided to do was modify the ASPPipeline HttpModule from my eBook. In ASP.NET there is an Application property on the current HttpContext. The Application property refers to the HttpApplication object for the web application. It defines many members at the application level, it is also allows you to add objects the same way you can to Session or ViewState. So what we are going to do here is just that, store a time value in the application object. Each time a page is requested my quasi singleton pattern will check to see if we have stored that value (object) and if not then store it.

Public ReadOnly Property StartTime() As String
    Get
        If IsNothing(HttpContext.Current.Application("StartTime")) Then
            HttpContext.Current.Application("StartTime") = Now.ToString
        End If
        Return HttpContext.Current.Application("StartTime").ToString
    End Get
End Property

This is a simple ReadOnly property called StartTime that returns a String. The first thing I do is to check and see if there is an object named “StartTime” established by using the IsNothing method. In C# the if statement would have used the != null check.

If the value has not been set then I set the value to the current time using the Now() method; HttpContext.Current.Application("StartTime") = Now.ToString.

Private Sub Application_BeginRequest(ByVal source As Object, _
        ByVal e As EventArgs)
    ' Create HttpApplication and HttpContext objects to access
    ' request and response properties.
    Dim application As HttpApplication = CType(source,  HttpApplication)
    sb.AppendFormat("BeginRequest - {0}{1}", Now.ToLongTimeString, vbCrLf)
 
    sb.AppendFormat("Start Time - {0}{1}", StartTime, vbCrLf)
 
End Sub

I will not go into the details of the HttpModule, there are other posts about custom HttpModules and my eBook, where I go into details about this module. But basically in the BeginRequest event handler I am going to set the value in the application object by calling the StartTime property. Now each time a request is made to an ASP.NET application the initial value will be logged to the log file, while the other times for each event in the ASP.NET life cycle will get stored at the time they are called.

Share this post :

Posted: Wednesday, September 10, 2008 7:38 AM

by Chris Love

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# September 10, 2008 11:22 AM

David L. Penton said:

You have a race condition here. It is possible on different threads to have the returned DateTime value be different if two threads enter the *if* branch before a value is set to "StartTime" and a third thread retrieves that value after thread 1 completes the activity but before thread 2 does.
# September 10, 2008 3:07 PM

john said:

sorry, but this is the worst example of a singleton i have ever seen.
# September 10, 2008 11:11 PM

Chris Love said:

David,

Thanks for pointing that out. You are right, I need to wrap setting the value in a locking mechanism.

John,

Sorry you feel that way, the purpose was more to show how to store a value at the application level. The context I was asked with a singleton and like I said I did not want to get into a real discussion of what a singleton is and I pointed that out.

# September 11, 2008 7:12 AM

Tony Bako - Agile Offshore said:

More Memcached - Enyim sample code

# June 12, 2009 11:44 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS