I'm working on a website and I need to display data from a JSON file.
Now the thing is, I need to get this data from an injected singleton service based on the user's language.
It should look something like that:
// Servies
services.AddSingleton<JsonLocalizationService>();
// Razor Page
@inject JsonLocalizationService
@JsonLocalizationService["nested"]["item"]
// file.en.json
{
"nested": {
"item": "Hello"
}
}
// file.ru.json
{
"nested": {
"item": "Привет"
}
}
The equivalent of the above code if I was using Shared Localization Service:
// Service
public class CommonResources
{
}
public class CommonLocalizationService
{
private readonly IStringLocalizer _localizer;
public CommonLocalizationService(IStringLocalizerFactory factory)
{
var assemblyName = new AssemblyName(typeof(CommonResources).GetTypeInfo().Assembly.FullName);
_localizer = factory.Create(nameof(CommonResources), assemblyName.Name);
}
public string Get(string key)
{
return _localizer.GetString(key);
}
}
services.AddSingleton<CommonLocalizationService>();
// Razor page
@inject CommonLocalizationService Localizer
@Localizer.Get("key") // This automatically gets the key in the localized file.
But the example above doesn't work with JSON and nesting.
The service needs to provide the appropriate file based on the user's language. (if English provide file.en.json if Russian provide file.ru.json)
How can I accomplish that?
I've looked into the source code of asp.net core but I didn't see where they were checking the language to switch between the files.