Translating EPiServer Category Description for EPiServer Find indexing

I had a requirement when I needed to translate EPiServer Category Description within product content's property. While it did work fine when viewing the product's page, EPiServer Find did not index it properly - it was using default language's value for each language.

After some investigation, I found that Category's LocalizedDescription property uses default behavior of LocalizationService. By default LocalizationService uses CultureInfo.CurrentUICulture to detect the current language for translation. Same time, EPiServer Find uses ContentLanguage.PreferredCulture but CultureInfo.CurrentUICulture is set to the default language.

The solution is quite simple - translate your property by providing your CultureInfo for LocalizationService. For EPiServer Find to be able to index localized version of it, use ContentLanguage.PreferredCulture.

public static class CategoryHelper
{
    public static string Translate(Category category)
    {
        var localizationService = ServiceLocator.Current.GetInstance<LocalizationService>();
        return localizationService.GetStringByCulture(
            $"/categories/category[@name=\"{category.Name}\"]/description",
            category.Description,
            ContentLanguage.PreferredCulture);
    }
}

Now you can use it in your page, product or other content.

public class MyProduct : ProductContent
{
    public virtual string CategoryName { get; set; }

    public string CategoryDescription => GetTranslatedCategoryDescription();

    public string GetTranslatedCategoryDescription()
    {
        var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
        var category = categoryRepository.Get(CategoryName);
        return CategoryHelper.Translate(category);
    }
}