9

I am looking for a way to resolve IStringLocalizer<T> objects with the real underlying resx files, using a similar method to how I resolved IOptions in this question.

This is in order to build unit tests that will chek each resx for each language to ensure the strings are implemented.

If it can't be done using the standard resolving of a IStringLocalizer<MyStringClass> type, then any other ways I can easily access the key value pairs from the resx would be helpful.

I've done some searching but not having much luck. Does anyone know of an easy way to do this?

Thanks in advance.

Chris
  • 7,996
  • 11
  • 66
  • 98
  • Have you checked the source repo to see how they do it for their unit tests? It should be able to give you some examples of how to adapt it to your use case. – Nkosi Sep 13 '17 at 12:15
  • The documentation should also be of some help https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization – Nkosi Sep 13 '17 at 12:19
  • According to docs `AddLocalization Adds the localization services to the services container.` – Nkosi Sep 13 '17 at 12:21

1 Answers1

18

You can directly instantiate a StringLocalizer instance, passing in a ResourceManagerStringLocalizerFactory to its constructor.

The ResourceManagerStringLocalizerFactory will take care of retrieving the actual localization values from the resource file.

So for example:

    using Microsoft.Extensions.Localization;
    using Microsoft.Extensions.Logging.Abstractions;
    using Microsoft.Extensions.Options;

    ...

public void MyTest() 
{
    var options = Options.Create(new LocalizationOptions());  // you should not need any params here if using a StringLocalizer<T>
    var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
    var localizer = new StringLocalizer<MyResourceFile>(factory);

    var myText = localizer["myText"];  // text using default culture

    CultureInfo.CurrentCulture = new CultureInfo("fr");
    var myFrenchText = localizer["myText"];  // text in French

}
RMD
  • 2,907
  • 30
  • 47
  • 1
    Perfect solution, but for me, it worked with Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr"); to change the culture. – Shadi Mar 09 '20 at 09:40
  • Thanks. This was the only example I could find. Microsoft's "documentation" had ZERO examples. – Mmm Apr 28 '23 at 17:44