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?
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
obj1will be initialized beforeobj2.You would only be able to “see”
obj1andobj2beforeInit()is called if you use their values in theClass1orClass2constructors (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.