Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pre-caching the single language Umbraco dictionary
#region
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Web.Dictionary;
#endregion
namespace MyApp
{
public class GeneralUmbracoEvents : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
CultureDictionaryFactoryResolver.Current.SetDictionaryFactory(new PreCachedDictionaryFactory());
}
}
public class PreCachedDictionaryFactory : ICultureDictionaryFactory
{
public ICultureDictionary CreateDictionary()
{
var dic = new PreCachedDictionary();
dic.Preload();
return dic;
}
}
public class PreCachedDictionary : ICultureDictionary
{
private readonly IDictionary<string, string> _preCachedDictionary = new Dictionary<string, string>();
private readonly ILocalizationService _localizationService;
private readonly ICacheProvider _requestCacheProvider;
public PreCachedDictionary()
: this(ApplicationContext.Current.Services.LocalizationService, ApplicationContext.Current.ApplicationCache.RequestCache)
{
}
public PreCachedDictionary(ILocalizationService localizationService, ICacheProvider requestCacheProvider)
{
_localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService));
_requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider));
}
public IDictionary<string, string> GetChildren(string key)
{
throw new NotImplementedException("I believe that this is not used anywhere. See UmbracoCultureDictionary.cs on Github");
}
public string this[string key] => _preCachedDictionary.ContainsKey(key) ? _preCachedDictionary[key] : string.Empty;
public CultureInfo Culture => System.Threading.Thread.CurrentThread.CurrentUICulture;
public void Preload()
{
_preCachedDictionary.Clear();
foreach (var item in _localizationService.GetDictionaryItemDescendants(null))
{
var byLang = item.Translations.FirstOrDefault(x => x.Language.Equals(Language));
if (byLang == null)
continue;
_preCachedDictionary.Add(item.ItemKey, byLang.Value);
}
}
private ILanguage Language
{
get
{
return _requestCacheProvider.GetCacheItem<ILanguage>(typeof (DefaultCultureDictionary).Name + "Culture" + Culture.Name,
() => _localizationService.GetLanguageByIsoCode(Culture.Name));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.