Load ViewEngine That is Used in Application : An ASP.Net MVC Performance Tip

This article discusses a tip for ASP.NET MVC that will helps in the performance of ASP.NET MVC applications. Let's discuss it.

Whenever we create an ASP.NET MVC application it allows us to select a ViewEngine for the application and by default the Razor View Engine as below.

select View engine.png

So as in the preceding screen shot Razor is selected from the dropdown.

But when the application runs, it loads multiple view engines and we use only one view engine normally that is selected during application creation. We can prove it in many ways.

1. Let's see the collection of ViewEngines in Global.asax. It shows while debugging.

firstall.png

The preceding clearly shows that it contains two View Engines while we selected Razor View Engine while creating application.

2. To prove it another way, as we know when we use the Razor View Engine the view's extension is .cshtml and for the WebForms view engine, it is .aspx. So let's say we created a controller and it has a method like:

 

  1. public ActionResult Index()  
  2. {  
  3.     return View();  
  4. }

And we did not create a view accordingly. Now when we run the applications it throws the following error:

serachedviews.png

It attempts to find the View but cannot find it. It also shows what file names it tries to fiind and where it tries to find them. If we see the preceding screenshot then we find that it looks for files with the extension .cshtml/.vbhtml and .aspx/ascs as well, where .aspx/.ascx is used in the case of the web-form's view engine. And we selected the Razor View Engine during application creation. It simply shows that it loads two view  engines that are not required.

Solution : Add the following code in the method Application_Start in Global.asax:

  1. // Removes all the view engine  
  2. ViewEngines.Engines.Clear();// Add View Engine that we are ging to use. Here I am using Razor View Engine  
  3. ViewEngines.Engines.Add(new RazorViewEngine());   

Now after making the preceding changes, it loads only the added (here Razor) view engine.

Now we can check the scenario discussed in point 2 and now see the page:

afterremovin.png

Now it tries to find only the .cshtml/.vbhtml files.

We should use the preceding logic and because there is no use of loading all the view engines in memory if we are not using them.