Joe Developer is tasked with displaying the start date of his ASP.NET application. Joe thinks he'll just add a DateTime field to global.asax and initialize the field during the Application_Start event.
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
StartDateTime = DateTime.Now;
}
public DateTime StartDateTime;
</script>
Whenever Joe needs to display the application start date, he accesses this public field.
Joe doesn't know what is wrong, but he is sure of one thing – the date that is displaying on his pages is not the date when the application started. Can you help out Joe one more time?
Comments
"You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of the HttpApplication class that is created."
Making the field static would get the code working - but why? :)
Tyrone:
You can get to fields, properties, and methods in global.asax. In an ASP.NET 2.0 web site you actually get a strongly typed ApplicationInstance property on the page that will reference an instance of the class that represents global.asax, so I could write "ApplicationInstance.StartDateTime" to fetch the value.
Notice I say "an instance" of the class. There is more than one instance alive, but only one of those instances will have StartDateTime initialized to the proper start time.
Eric: Correct. The code in global.asax ends up inside a class derived from HttpApplication. There will be multiple instances of this class in a pool to serve requests, and this is why using the static keyword with that field is one way to fix the problem.
In this case we'll assume Joe only reads the field after the app starts, so it's thread safe (ASP.NET guarantees Application_Start is only called once).
The first instance gets assigned a value because it's the only one that actually fires Application_Start. All others get what? DateTime.MinValue?
Actually I would argue that putting any properties on HttpApplication is a bad idea precisely because of the confusion about lifetime of HttpApplication, but also even if you use a static you can only reference it directly through this particular class. If you use context.ApplicationInstance the var won't show up (even a public instance variable won't) because the instance is cast to HttpApplication.
For statics that are 'application' level I'd recommend using a separate class - I tend to use App. I hang things like a global configuration object off off that App.Configuration, App.APP_NAME, App.EMPTY_DATE, App.StateLookupTable etc. are then accessible anywhere.
Yes, when left untouched it comes out as DateTime.MinValue (1/1/0001). I do agree about staying away from HttpApplication.
msdn2.microsoft.com/en-us/library/ms998558.aspx