Search code examples
asp.netstaticstatic-classesstatic-constructorstatic-class

asp.net: Will the static constructor be called every time there is a postback to a page?


This could be a possible duplicate of Asp.net Static Variable Life time Across Refresh and PostBack but my query is a little different.

I have a web application with a page namely default.aspx. I have a public static class "MyClass" with a static constructor and a static property "MyProperty", This class is outside default.aspx.cs class.

The property of the static class is getting assigned on page load and on a button click.

Now, I know that static constructor of a type will get called only once whenever any property of the class is called or assigned. This is per AppDomain. After that static constructor will never get called.

I also know that An app domain is a .NET construct that provides a layer of isolation between loaded sets of assemblies within a process.

So my questions here are

  1. Could someone please elaborate AppDomain in terms of asp.net? Any related link will also help.
  2. I know that the page object is created and destroyed on each postback. So, for the following code, will the static constructor called every time there is a postback?

I tried debugging the code by keeping breakpoint on static constructor. The breakpoint got hit when the first time the page loaded but did not when I clicked on the button. But I am not sure if this will work the same way when hosted on IIS so wanted to get some expert opinion. The browser was IE10.

Please let me know if I have not framed any sentence correctly or stated something wrong.

Thanks in advance.

Regards,

Samar

public static class MyClass
{
    public static int MyProperty { get; set; }
    static MyClass()
    { 
    }
}
public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        MyClass.MyProperty = 2;
    }



    protected void Button1_Click(object sender, EventArgs e)
    {
        MyClass.MyProperty = 1;
    }
}

Solution

  • I think this page What ASP.NET Programmers Should Know About Application Domains does a pretty good job of explaining Application Domains.

    The static constructor will only get called once and not per post back (as you've also seen), I don't believe you should expect any different behavior based on the browser or IIS.