Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put initializing code in an ASP.Net MVC app?

Tags:

.net

asp.net

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?

like image 615
Henley Avatar asked Apr 23 '13 15:04

Henley


3 Answers

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.

like image 175
aquaraga Avatar answered Nov 13 '22 08:11

aquaraga


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.

like image 40
AaronLS Avatar answered Nov 13 '22 07:11

AaronLS


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));
like image 42
Steve Wortham Avatar answered Nov 13 '22 07:11

Steve Wortham