tags:

views:

117

answers:

3

I have an extension method which uses some configuration settings. I've declared these as static.

public static class Extensions
{
    static string _mailServer = ConfigurationManager.AppSettings["MailServer"];
    // ... etc    

    public static void SendEmailConfirmation(this IOrder order) { }
}

I just wanted to check that this is doing what I intend as I'm not 100% sure. The idea is that I don't want to have to keep reading these values, I'd like them to be read once and cached for the lifetime of the web application. Is this what will happen? Thanks

+9  A: 

(updated with KeithS's clarification that they aren't read until first used)

They will be read the first time they are used, and then retained until the AppDomain is stopped or recycled, which is probably what you want.

That is, ASP.NET apps run inside an AppDomain. This is how they are resident and available to multiple requests without having to startup for each individual request. You can configure how long they live and when they recycle, etc. Static variables live and die with the app and thus will survive as long as the app is resident in the app domain.

Michael Haren
cool, thanks. (easiest rep points ever for you :))
fearofawhackplanet
Yes, until a dozen people come in to clarify all the edge cases where this isn't 100% true... ;)
Michael Haren
Basically this. More specifically, statics are lazily evaluated when they are first needed. This saves startup costs of initializing a bunch of statics up front. So, the first time you run SendEmailConfirmation(), it will access the app setting, and will persist it for the life of the app domain (which will run until the app pool or IIS is reset; the first happens automatically from time to time, the other happens by user choice or on a server reboot)
KeithS
At what point does the AppDomain start?
user279521
thanks, @keiths
Michael Haren
@user279521 I think the default configuration in IIS will start the app domain when a user hits the site. Then it will stop the app domain if nothing hits it for a while (15 minutes?). I often change these limits so a less frequently used app stays up longer to avoid a huge delay for that poor first user
Michael Haren
so is that synch'ed with session object?
user279521
@user279521, yes, if it's inproc session http://aspalliance.com/226
Michael Haren
very cool. Thanks @Michael.
user279521
+1  A: 

_mailServer will be initialized the first time the Extensions class is used (in any way). It will not be set again until the app domain is reloaded.

James Curran
+1  A: 

They'll be loaded the first time they're needed and will then stay in memory until IIS recycles the app.

Esteban Araya