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?
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With