views:

37

answers:

3

I have a ASP.NET MVC project that has a static class in it to initialize some AutoMapper mappings:

static class AutoMappingConfiguration
{
    static AutoMappingConfiguration()
    {
        SetupMappings();
    }

    static void SetupMappings()
    {
        AutoMap.CreateMap<Product, ProductDTO>();
        // more mappings
    }
}

Setting a breakpoint in the static constructor shows me that it's never hit when I run the project. I have to explicitly call the method in MvcApplication.Application_Start():

AutoMappingConfiguration.SetupMappings();

Does anyone know why this static class is not being constructed by ASP.NET MVC? Does this have to do with the 'on-the-fly compilation' nature of IIS? If so, do I have to explicitly call the static method, or is there some way of configuring the project to initialize static classes?

A: 

I believe the code does get executed and you don't see it because you don't attach the debugger on time.

Verify this by having code that write to text file and see if the text file has been created:

static AutoMappingConfiguration()
{
    File.WriteAllText("C:\\mytestfile.txt", "AutoMappingConfiguration executed");
    SetupMappings();
}
Shadow Wizard
+1  A: 

Classes are initialised before the first time any of it's members are used. If you never use the class, the static constructor is never called.

Guffa
+5  A: 

The static constructor isn't called unless either an instance of the class is created or any static method is called, that's the documented/expected behavior. So you'll have to call that static method (or any other method in the class) to get it called.

steinar
You don't have to call a method, you just have to use any of the members.
Guffa
Yes, to be precise: use it in any way.
steinar
Wow thanks, I never realized that before. This is the first static class I've created where I only want the constructor to execute.
Daniel T.
@Daniel Side note: A pattern you *could* use in such cases - where you want the static constructor to be called - would be having a (possibly empty) static function called for example `Initialize()`, its sole purpose being to ensure that the static constructor would be called. That's practical when there is some heavy logic in the constructor which you want to be called at startup time rather than when, for example, a page load triggers it. That would prevent your users from experiencing the lag involved.
steinar