genki98
genki98

Reputation: 780

static variables in web site and web application C#

I have same codes which work differently on 2 different IIS servers which one is set as web site and another is set as web application.

I have 2 classes.

public class Config1{
    public static string RelativePath {get; set;}
}

public class Config2{
    public static readonly string FavIconPath = Config1.RelativePath;
}

And I assign value from web.config in Global.asax.cs

protected void Application_Start(){
    Config1.RelativePath = getWebConfigValue("Path");
}

I use it in view files like below.

RelativePath : @Config1.RelativePath<p/>
FavIconPath : @Config2.FavIconPath

The results are

On web site server
RelativePath : somevalue
FavIconPath : 

On web application server
RelativePath : somevalue
FavIconPath : somevalue

Is there any differences of instantiate timing between web site and web application? Any help would be appreciated!

Upvotes: 0

Views: 142

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

Static field initializers such as the one assigning the initial value to Config2.FavIconPath are processed when the type (Config2) is first referenced. This typically happens when your code first accesses it, but it may happen sooner.

The value of Config1.RelativePath changes after the Application_Start() method is called, so the actual value used for the FavIconPath depends on the order of the Application_Start() method and the Config2 type to be loaded.

Even though I don't know what happens under the hood, this code shows why you should not let code depend on framework internal behavior.

Upvotes: 2

Related Questions