2

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?

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You don't have to call a method, you just have to use any of the members.
Yes, to be precise: use it in any way.
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 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.
3

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.

Comments

1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.