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
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 !!