Understand the difference between AddMvc() and AddMvcCore()

As a beginner, you must have stumbled upon these two methods - AddMvc() and AddMvcCore() - in the ConfigureServices() of the Startup class. you must have wondered about the difference between them. This article quickly points out the difference between the two.

If you open the Startup class and go to its ConfigureServices() method you will find two methods in the IServiceCollection - AddMvc() and AddMvcCore(). The following figure shows them in the Visual Studio editor.

These two methods sound quite similar and their respective help tooltips simply tell us this :

  • Adds MVC services to the specified IServiceCollection
  • Adds essential MVC services to the specified IServiceCollection

So, what's the difference between them?

To understand the difference between these two extension methods let's see their source code from the GitHub repository.

The source code of AddMvc() method can be found here and that of AddMvcCore() can be found here.

The AddMvcCore() method is shown below :

I wont go into the details of this method. It suffices to say that AddMvcCore() performs certain basic operations such as controller management and routing.

The fragment of the source code of AddMvc() is given below :

Notice that AddMvc() calls AddMvcCore(). So, obviously AddMvc() provides more functionality than AddMvcCore(). If you carefully observe the source code of AddMvc() you will find that it adds more features such as CORS support, Razor View Engine, data annotations, Cache tag helper, and the JSON formatter.

Ok. Now you know the difference between AddMvc() and AddMvcCore(). But what will happen if you try to use AddMvcCore() instead of AddMvc()?

Well, go ahead and do that in a simple "Hello World" application. You will get the following result in the browser :

This error indicates that view related features are not available for our application. And that's because we used AddMvcCore() instead of AddMvc().

Can we fix this error? Yes. Just manually add Razor view engine support and view support. The following code shows how this can be done :

We called AddViews() and AddRazorViewEngine() methods ourselves. You will need to add all the required features manually if you prefer to use that approach. Now the application will work as expected :

That's it for now ! Keep coding !!

Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Kriya and Meditation online course are available here.

Posted On : 17 September 2018

Tags : ASP.NET ASP.NET Core MVC .NET Framework C#