0

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.

1 Answer 1

1

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()
    {

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

2 Comments

1. I want to have some info structures which to be initialized once (something like const but not exactly). Don't want these structures to be initialized every time. Since I'll have only read operation I don't need synchronization. I know that I can use Cache and Application, but that way I'll give visibility to all my controllers to these structures and don't want to, since I'll use them in just one. I'm not saying that my way is the right way, so if someone can offer a better solution to my situation please do.
2. My static constructor signature is exactly as the one you wrote. I'm trying to debug it and put 2 break points in static and normal constructor. The normal constructor is called before static one. Any ideas why?

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.