I\'m using ASP.NET Core, and trying to localize the application. I managed to use new asp .net core resources to localize controllers and views, and old re
With reference to this post that describes in detail the side effects for using BuildServiceProvider inside ConfigureServices, and to this answer regarding resolving services inside ConfigureServices, last but not least, considering the refered improved answer by Andrew Lock, the correct approach to localize model binding error messages should be by creating a custom configuration class that implements IConfigureOptions then registering it in startup as below:
public class ConfigureModelBindingLocalization : IConfigurationOptions
{
private readonly IServiceScopeFactory _serviceFactory;
public ConfigureModelBindingLocalization(IServiceScopeFactory serviceFactory)
{
_serviceFactory = serviceFactory;
}
public void Configure(MvcOptions options)
{
using(var scope = _serviceFactory.CreateScope())
{
var provider = scope.ServiceProvider;
var localizer = provider.GetRequiredService();
options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) =>
localizer["The value '{0}' is not valid for {1}.", x, y]);
options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) =>
localizer["A value for the '{0}' parameter or property was not provided.", x]);
options.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() =>
localizer["A value is required."]);
options.ModelBindingMessageProvider.SetMissingRequestBodyRequiredValueAccessor(() =>
localizer["A non-empty request body is required."]);
options.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) =>
localizer["The value '{0}' is not valid.", x]);
options.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() =>
localizer["The supplied value is invalid."]);
options.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() =>
localizer["The field must be a number."]);
options.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) =>
localizer["The supplied value is invalid for {0}.", x]);
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) =>
localizer["The value '{0}' is invalid.", x]);
options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) =>
localizer["The field {0} must be a number.", x]);
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) =>
localizer["The value '{0}' is invalid.", x]);
}
}
}
Finally register the new configuration class in startup:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton, ConfigureModelBindingLocalization>();
// ...
}