Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve IStringLocalizer with real resx manually

Tags:

c#

.net

.net-core

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.

like image 365
Chris Avatar asked Sep 13 '17 12:09

Chris


1 Answers

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

}
like image 132
RMD Avatar answered Nov 13 '22 15:11

RMD