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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With