是否可以IOptions<AppSettings>从ConfigureServicesStartup中的方法解析实例?通常,您可以使用IServiceProvider初始化实例,但在注册服务时此阶段没有实例.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(
configuration.GetConfigurationSection(nameof(AppSettings)));
// How can I resolve IOptions<AppSettings> here?
}
Run Code Online (Sandbox Code Playgroud) TLDR;如何获得行为
[Required(ErrorMessage = "Le champ {0} est obligatoire")]
Run Code Online (Sandbox Code Playgroud)
虽然只是写作
[Required]
Run Code Online (Sandbox Code Playgroud)
据我了解,该文档没有提供一种隐式本地化一组给定 DataAnnotations 的方法。
我希望有注释的错误消息,例如Required和StringLength可以覆盖而不触及其他人,例如Display并且不需要使用ErrorMessage属性明确指定翻译。
注意:我只需要将消息翻译成法语,因此不需要将解决方案绑定到请求的语言。
我尝试了以下方法:
从这个GitHub 线程
在里面 Startup.cs
services.AddMvc(options => options.ModelBindingMessageProvider.AttemptedValueIsInvalidAccessor =
(value, name) => $"Hmm, '{value}' is not a valid value for '{name}'."));
Run Code Online (Sandbox Code Playgroud)
给了我以下错误
无法分配属性或索引器“DefaultModelBindingMessageProvider.AttemptedValueIsInvalidAccessor”——它是只读的
我找不到任何可以作为这个对象的 setter 的属性。
从这个SO答案
在Startup.cs
services.AddSingleton();
并创建一个类,如跟随
public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();
public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
{ …Run Code Online (Sandbox Code Playgroud) 如何本地化 ASP.NET Core (v2.2) 中验证属性的标准错误消息?例如,[Required]属性有此错误消息“ The xxx field is required. ”;[EmailAddress]有“ xxx 字段不是有效的电子邮件地址。 ”;【比较】有“ 'xxx'和'yyy'不匹配。 ”等。在我们的项目中,我们不使用英语,我想找到一种方法来翻译标准错误消息,而不直接将它们写入每个数据模型类的每个属性中
c# validationattribute asp.net-core-localization asp.net-core-2.2
有时,在服务注册期间,我需要从DI容器解析其他(已注册)服务。使用Autofac或DryIoc之类的容器,这没什么大不了的,因为您可以在一行上注册该服务,而在下一行上可以立即解决该问题。
但是,使用Microsoft的DI容器,您需要注册服务,然后构建服务提供程序,然后才可以从该IServiceProvider实例解析服务。
请参阅以下SO问题的可接受答案:ASP.NET核心模型绑定错误消息本地化
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
services.AddMvc(options =>
{
var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = F.Create("ModelBindingMessages", "AspNetCoreLocalizationSample");
options.ModelBindingMessageProvider.ValueIsInvalidAccessor =
(x) => L["The value '{0}' is invalid."];
// omitted the rest of the snippet
})
}
Run Code Online (Sandbox Code Playgroud)
为了能够对ModelBindingMessageProvider.ValueIsInvalidAccessor消息进行本地化,答案建议IStringLocalizerFactory通过基于当前服务集合构建的服务提供商来解决。
那时“构建”服务提供者的成本是多少,并且这样做会有任何副作用,因为将至少再次构建一次服务提供者(在添加所有服务之后)?