fearofawhackplanet
fearofawhackplanet

Reputation: 53396

Lifetime of static variables in .NET

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

Upvotes: 10

Views: 7860

Answers (3)

Michael Haren
Michael Haren

Reputation: 108256

(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.

Upvotes: 16

Esteban Araya
Esteban Araya

Reputation: 29664

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

Upvotes: 1

James Curran
James Curran

Reputation: 103515

_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.

Upvotes: 1

Related Questions