Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public interface ISitecoreLocalizer : IStringLocalizer
{
Task Reload();
}
public class SitecoreLocalizer : ISitecoreLocalizer
{
private static readonly Dictionary<string, Dictionary<string, string>> _sitecoreDictionary = new Dictionary<string, Dictionary<string, string>>();
private readonly HttpClient _httpClient;
private readonly SitecoreLocalizerOptions _sitecoreLocalizerOptions;
private readonly IHttpContextAccessor _httpContextAccessor;
public SitecoreLocalizer(
IHttpClientFactory httpClientFactory,
IOptions<SitecoreLocalizerOptions> sitecoreLocalizerOptions,
IHttpContextAccessor httpContextAccessor)
{
_httpClient = httpClientFactory.CreateClient("sitecoreLocalizer");
_sitecoreLocalizerOptions = sitecoreLocalizerOptions?.Value;
_httpContextAccessor = httpContextAccessor;
}
public LocalizedString this[string name]
=> new LocalizedString(name, _sitecoreDictionary[_httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>().RequestCulture.Culture.ToString()][name]);
public LocalizedString this[string name, params object[] arguments]
=> new LocalizedString(name, string.Format(_sitecoreDictionary[_httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>().RequestCulture.Culture.ToString()][name], arguments));
public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
{
foreach (var dictionaryItem in _sitecoreDictionary[_httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>().RequestCulture.Culture.ToString()])
{
yield return new LocalizedString(dictionaryItem.Key, dictionaryItem.Value);
}
}
public async Task Reload()
{
foreach (var culture in _sitecoreLocalizerOptions.Cultures)
{
var response = await _httpClient.GetAsync(_httpClient.BaseAddress.AbsoluteUri.Replace("[language]", culture.ToString()));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
_sitecoreDictionary[culture.ToString()] = JsonConvert.DeserializeObject<DictionaryModel>(content).Phrases;
}
}
}
public IStringLocalizer WithCulture(CultureInfo culture)
{
throw new System.NotImplementedException();
}
}
public class DictionaryModel
{
public Dictionary<string, string> Phrases { get; set; }
}
public class SitecoreLocalizerOptions
{
public IEnumerable<CultureInfo> Cultures { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment