是否允许多次调用 AddRazorPages?

Is multiple calls of AddRazorPages allowed?

在 Program.cs 中,我调用 AddRazorPages 来设置 Fluent Validation 和一些本地化内容。不幸的是,这有很多重复代码,我想知道通过两次调用 AddRazorPages 来减少它是否完全合法?

我已经尝试 运行 代码并且它似乎可以工作,但是任何人都可以确认新版本与旧版本实际上相同吗?

当前Program.cs

if (isDevelopment)
    // Run-time compilation added during development
    builder.Services.AddRazorPages(options => options.Conventions.Add(new CultureTemplatePageRouteModelConvention()))
        .AddFluentValidation(fv =>
        {
            fv.RegisterValidatorsFromAssemblyContaining<PersonValidator>();
            fv.LocalizationEnabled = true;
            fv.DisableDataAnnotationsValidation = false;
        })
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization()
        .AddRazorRuntimeCompilation();
else
    // No Run-time compilation needed when deployed
    builder.Services.AddRazorPages(options => options.Conventions.Add(new CultureTemplatePageRouteModelConvention()))
        .AddFluentValidation(fv =>
        {
            fv.RegisterValidatorsFromAssemblyContaining<PersonValidator>();
            fv.LocalizationEnabled = true;
            fv.DisableDataAnnotationsValidation = false;
        })
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();

新建Program.cs

builder.Services.AddRazorPages(options => options.Conventions.Add(new CultureTemplatePageRouteModelConvention()))
    .AddFluentValidation(fv =>
    {
        fv.RegisterValidatorsFromAssemblyContaining<PersonValidator>();
        fv.LocalizationEnabled = true;
        fv.DisableDataAnnotationsValidation = false;
    })
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

// Run-time compilation added during development
if (isDevelopment)
    builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

您可以多次拨打 AddRazorPages。在内部,它使用一系列 TryAdd* 调用来添加该方法负责注册的各种服务。如果服务已经注册到服务容器,则什么也不会发生。

https://github.com/dotnet/aspnetcore/blob/207f2c39ee1eccbc339450570fe6297026ea549c/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcCoreBuilderExtensions.cs#L95