Wei Ma
Wei Ma

Reputation: 3155

Running order of static code

I am working on a project using .Net mvc. I have a csharp class containing both a static constructor and some static filed.

    private static Class1 obj1 = new Class1();
    private static Class2 obj2 = new Class2();


    static Foo()
    {
       Init();
    }

   private static void Init()
   {
       obj1.DoSomething();
       obj2.DoSomething();
   }

This class is part of my DomainModel, and is referenced in my Controller code. When I run the project with VS2008. It seems Init() is called before the Controller code uses obj1 and obj2. But when I deploy the code to a virtual server, Init() seems not being called at all. Is there any way to guarantee the execution order of these methods?

Upvotes: 0

Views: 189

Answers (4)

Wei Ma
Wei Ma

Reputation: 3155

OK, I have found the problem. The real problem is some funky I18n problem. When I start the application with vs2008, the parameter passed from view to my controller is encoded with GB2312, and when I deployed to a virtual server, the parameter is encoded with utf-8 with corrupted value. I have no idea how to configure the virtual server to send values in GB2312, so I just removed the dependencies for my Chinese strings and things work fine again. Thanks for your all wonderful answers.

Upvotes: 0

Jirapong
Jirapong

Reputation: 24256

I'm not fully understand your question. assume that you want to do some action before each Action being call then "Action Filter" is your friend. See this link

Upvotes: 0

Maximilian Mayerl
Maximilian Mayerl

Reputation: 11357

Well, I'm pretty shure it is called. When you use a static constructor in C#, C# applies the "beforefieldinit" attribute to your class, so the static constructor is guaranteed to be called at some point before the static members of type are used for the first time.

So, are you shure you actually use the static members? If you don't there is no guarantee the static constructor will execute.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

Assuming you do genuinely reference this class (not just static methods in a derived class) then the C# specification guarantees that the static variables are initialized, then the static constructor is executed. Likewise, assuming no partial classes are involved, the C# spec guarantees that obj1 will be initialized before obj2.

You would only be able to "see" obj1 and obj2 before Init() is called if you use their values in the Class1 or Class2 constructors (as those constructors will be called as part of initializing the static variables).

Now, it's hard to talk in more concrete terms than that without seeing the rest of your code. If you can produce a short but complete example which demonstrates the problem, that would be easier to discuss in detail.

Upvotes: 6

Related Questions