6

I have a ASP.NET MVC4 web app, and I want some code to be executed the first time an app starts. The code basically loads a bunch of data from the database and stores it in a cache, so that any future requests can look up the data from the cache.

Where is the correct place to put this code? Should I simply add my line of code to Global.asax, or is there a best practice for calling code once an app starts?

3 Answers 3

8

Have a separate class to do the data initialization and call the respective method from Global.asax. The Global.asax should basically serve as an orchestrator. The individual initializations such as DI container initialization, cache initialization, route initialization etc. should sit in their own classes, thus honouring the single responsibility principle.

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

Comments

4
Global.asax.cs:Application_Start()

Same place you do things like register routes.

This is exactly where I initialize caches as well. I also check the cache expiration time on each Application_BeginRequest() to see if it needs to be updated.

Comments

2

You could place the code in Application_Start in Global.asax.

Or you could use the Lazy type on a static member, and it'll only initialize when it's first called (and it remains in memory for as long as the application runs). This has the advantage of not slowing application start up unnecessarily.

For instance, this example is for a compiled Regex, but could also be done with loading data:

public static Lazy<Regex> LibraryTagsRegex = 
    new Lazy<Regex>(() => new Regex(@"^library/tagged/(?<Tags>.+)", RegexOptions.Compiled));

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.