Single Fighter Single Fighter - 1 month ago 35
ASP.NET (C#) Question

When I develop ASP.NET Core MVC, which service should I use? AddMvc or AddMvcCore?

I am learning ASP.NET Core MVC from a book, the code snippet in question is as follows,

enter image description here

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();// or
//services.AddMvc();
}


Questions



Is what I do here correct?

Answer

Have a look at the MvcServiceCollectionExtensions.cs class on the ASP.NET Core MVC 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.AddCacheTagHelper();

    // +1 order
    builder.AddDataAnnotations(); // +1 order

    // +10 order
    builder.AddJsonFormatters();

    builder.AddCors();

    return new MvcBuilder(builder.Services, builder.PartManager);
}

AddMvc() internally calls AddMvcCore() and adds other middleware such as the Razor view engine, JSON formatters, CORS, etc.

I haven't messed around as much as I'd have liked to with ASP.NET Core MVC yet, but it would appear that AddMvcCore(), as the name implies, only adds core components, requiring you to add any other middleware (needed for your project) by yourself.

For now, I would follow what your tutorial suggests and stick to AddMvc().