devfreak
devfreak

Reputation: 1231

Asp.Net Mvc controller static constructor

I'm trying to create a site, with a master controller.It has two constructors - static and parameterless. By specification the static one should be called first and once, to initialize static members of the class, but it never did, why is that? How can I implement single storage for some staff which should be accessible from the controller?

EDIT: I guess I make some mistake when I try to debug it because, today it works like expected, static constructor is called once and before regular one.

Upvotes: 0

Views: 4305

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

It's not very common to use static constructors for controllers in ASP.NET MVC. I don't know what exactly are you trying to achieve but global.asax Application_Start seems like a better place to perform application initializations. Also what do you mean by a single storage accessible by the controller? Can't you use the HttpContext.Cache or the HttpContext.Application object which are used for storing application wide things (in contrast to session)? They also have the advantage to be thread safe so that you don't need to synchronize the access to those storages.

As far as the static controller constructor is concerned it should be called before the default constructor and only once per application and that's guaranteed by the CLR. For this it needs to have exactly the following signature (private, no return type, same name as the containing type):

public class HomeController: Controller
{
    // This is the exact signature of a static constructor
    static HomeController()
    {

    }
}

Upvotes: 1

Related Questions