在Program.cs中,我正在调用AddRazorPages来设置流畅验证和一些本地化的东西。不幸的是,这有很多重复的代码,我想知道如果它是完全合法的,通过调用AddRazorPages两次减少它?
我试着运行代码,它似乎工作,但谁能确认新版本是有效地与旧版本相同?
当前Program.csif (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.csbuilder.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