2
votes

In .Net Core official documentation for localization, it is mentioned how to make DataAnnotations to be localized by IStringLocalizer from either a special resx file named by special .Net Core naming convention:

For example:
Resources/ViewModels.Account.RegisterViewModel.fr.resx Resources/ViewModels/Account/RegisterViewModel.fr.resx

or from SharedResource.resx file, from where ALL DataAnnotations will be localized:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

In the preceeding code, SharedResource is the class corresponding to the resx where your validation messages are stored. With this approach, DataAnnotations will only use SharedResource, rather than the resource for each class.

What I actually need to achieve is: defining which DataAnnotations will be localized from the SharedResource.resx file, and which one will be localized from ViewModel-specific.resx file. Is this somehow possible? In other words, I do not want to localize from different *.resx sources (where the fall-back value is the SharedResource.resx).

1
I don't think that is possible. If you specify .AddDataAnnotationsLocalization() without any special option, the class-specific resx files will be used. If you use the option shown in your example, then the shared resx file will be used. I don't think there is any middle way between these options and I don't think that there is a fallback from the class-specific file to the shared resx file. It might be possible to write your own implementation of IStringLocalizer and IStringLocalizerFactory (but I personally doubt if that is a good idea). - Phil Jollans
There is a link to an implementation of IStringLocalizer and IStringLocalizerFactory from this page. The link is to this project. I have no idea it works. - Phil Jollans
@PhilJollans, it is not an implementation. He is trying to find a workaround the lacked DisplayName localization (which is now fixed in .Net Core 2.0). - Mohammed Noureldin
I understand. I just thought that, if you wanted to make a custom implementation of IStringLocalizer to fix your problem, that might be a starting point. - Phil Jollans
Did you found the solution for this ? - Jean-Francois

1 Answers

0
votes