ASP.NET Core 中 AddMvc() 與 AddMvcCore() 的差別

  • 1274
  • 0

ASP.NET Core 中 AddMvc() 與 AddMvcCore() 的差別

1. AddMvcCore 介紹

  • 部份程式碼
public static IMvcCoreBuilder AddMvcCore(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }
    var partManager = GetApplicationPartManager(services);
    services.TryAddSingleton(partManager);
    ConfigureDefaultFeatureProviders(partManager);
    ConfigureDefaultServices(services);
    AddMvcCoreServices(services);
    var builder = new MvcCoreBuilder(services, partManager);
    return builder;
}

2. AddMvc 介紹

  • 部份程式碼
public static IMvcBuilder AddMvc(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }
    services.AddControllersWithViews();
    return services.AddRazorPages();
}
....
public static IMvcBuilder AddControllersWithViews(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }
    var builder = AddControllersWithViewsCore(services);
    return new MvcBuilder(builder.Services, builder.PartManager);
}
private static IMvcCoreBuilder AddControllersWithViewsCore(IServiceCollection services)
{
    var builder = AddControllersCore(services)
        .AddViews()
        .AddRazorViewEngine()
        .AddCacheTagHelper();
    AddTagHelpersFrameworkParts(builder.PartManager);
    return builder;
}
....
private static IMvcCoreBuilder AddControllersCore(IServiceCollection services)
{
    // This method excludes all of the view-related services by default.
    return services
        .AddMvcCore()
        .AddApiExplorer()
        .AddAuthorization()
        .AddCors()
        .AddDataAnnotations()
        .AddFormatterMappings();
}

3. 兩者主要差別:

  1. 以程式碼來看AddMvcAddMvcCore多了下列內容
    1. AddRazorPages
    2. AddViews
    3. AddRazorViewEngine
    4. AddCacheTagHelper
    5. AddApiExplorer
    6. AddAuthorization
    7. AddCors
    8. AddDataAnnotations
    9. AddFormatterMappings