Skip to content

Instantly share code, notes, and snippets.

@trnktms
Last active June 8, 2021 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trnktms/5982956bb7ad0e5392b1f85b752ebdd9 to your computer and use it in GitHub Desktop.
Save trnktms/5982956bb7ad0e5392b1f85b752ebdd9 to your computer and use it in GitHub Desktop.
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