Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my static class not being initialized in ASP.NET MVC?

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?

like image 213
Daniel T. Avatar asked Jan 24 '26 01:01

Daniel T.


1 Answers

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.

like image 115
steinar Avatar answered Jan 26 '26 18:01

steinar