Should I use AddMvc or AddMvcCore for ASP.NET Core MVC development?
C#asp.net Core-MvcC# Problem Overview
I am learning ASP.NET Core MVC from a book, the code snippet in question is as follows:
// CHAPTER 4 - ESSENTIAL C# FEATURES
namespace LanguageFeatures {
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
}
// etc.
Because the book is about ASP.NET Core MVC rather than ASP.NET MVC, I think I have to use AddMvcCore()
rather than AddMvc()
as follows:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore(); // as opposed to:
//services.AddMvc();
}
Is what I do here correct?
C# Solutions
Solution 1 - C#
Have a look at the MvcServiceCollectionExtensions.cs
class on the ASP.NET Core GitHub repo:
public static IMvcBuilder AddMvc(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var builder = services.AddMvcCore();
builder.AddApiExplorer();
builder.AddAuthorization();
AddDefaultFrameworkParts(builder.PartManager);
// Order added affects options setup order
// Default framework order
builder.AddFormatterMappings();
builder.AddViews();
builder.AddRazorViewEngine();
builder.AddRazorPages();
builder.AddCacheTagHelper();
// +1 order
builder.AddDataAnnotations(); // +1 order
builder.AddCors();
return new MvcBuilder(builder.Services, builder.PartManager);
}
AddMvcCore()
and AddMvc()
both return an IMvcBuilder
that can be used to further configure the MVC services.
AddMvcCore()
, as the name implies, only adds core components of the MVC pipeline, requiring you to add any other middleware (needed for your project) by yourself.
AddMvc()
internally calls AddMvcCore()
and adds other middleware such as the Razor view engine, Razor pages, CORS, etc.
For now, I would follow what your tutorial suggests and stick to AddMvc()
.
As of ASP.NET Core 3.0, there are additional methods that give fine-grained control over what portions of the MVC pipeline are available to your application, e.g.:
Refer to this article and MSDN for more information about what they do and when to use them.