Where to put initialization code in an ASP.Net MVC application?

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

Where is the place to put this code? Should I just add my line of code to Global.asax, or is there any best practice for calling code after running the application?

+6
source share
3 answers

Have a separate class to initialize the data and call the appropriate method from Global.asax . Global.asax should mainly act as an orchestra. Individual initializations, such as DI container initialization, cache initialization, route initialization, etc., Must be placed in their own classes, thereby observing the principle of common responsibility.

+6
source
 Global.asax.cs:Application_Start() 

In the same place you do things like check-in routes.

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

+4
source

You can put the code in Application_Start in Global.asax.

Or you can use the Lazy type for a static member, and it will only be initialized on the first call (and remains in memory for as long as the application is running). This has the advantage of not slowing down the launch of the application unnecessarily.

For example, this example is for compiled Regex, but can also be executed with data loading:

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

Source: https://habr.com/ru/post/943446/


All Articles