Skip to content

Instantly share code, notes, and snippets.

@valdisiljuconoks
Created December 29, 2017 09:01
Show Gist options
  • Save valdisiljuconoks/ebcd8db758801698bfe14a298cdf5cf6 to your computer and use it in GitHub Desktop.
Save valdisiljuconoks/ebcd8db758801698bfe14a298cdf5cf6 to your computer and use it in GitHub Desktop.
[InitializableModule]
[ModuleDependency(typeof(ServiceContainerInitialization))] // used to override default provider
public class CustomProviderBasedLocalizationService : ProviderBasedLocalizationService, IConfigurableModule
{
private static LocalizationService _localizationService;
public CustomProviderBasedLocalizationService() : this(null) { }
public CustomProviderBasedLocalizationService(ResourceKeyHandler keyHandler) : base(keyHandler) { }
public new void ConfigureContainer(ServiceConfigurationContext context)
{
// register as a factory
context.Services.AddSingleton(typeof(LocalizationService),
locator =>
CreateCustomProviderBasedLocalizationService(locator.GetInstance<ResourceKeyHandler>(),
locator.GetInstance<LocalizationOptions>(),
locator));
}
protected override string LoadString(string[] normalizedKey, string originalKey, CultureInfo culture)
{
var list = ProviderList.ToList(); // important fix for collection was modified issue
foreach(var provider in list)
{
var str = provider.GetString(originalKey, normalizedKey, culture);
if(str != null)
return str;
}
return null;
}
public static LocalizationService CreateCustomProviderBasedLocalizationService(
ResourceKeyHandler keyHandler,
LocalizationOptions localizationOptions,
IServiceLocator serviceLocator)
{
if(_localizationService != null)
return _localizationService;
ProviderBasedLocalizationService localizationService = new CustomProviderBasedLocalizationService(keyHandler);
foreach(var providerFactory in localizationOptions.Providers)
localizationService.AddProvider(providerFactory.Build(serviceLocator));
localizationService.FallbackBehavior = localizationOptions.FallbackBehavior;
localizationService.FallbackCulture = localizationOptions.FallbackCulture;
_localizationService = localizationService;
return _localizationService;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment