Skip to content

Instantly share code, notes, and snippets.

@salaros
Created July 14, 2018 14:55
Show Gist options
  • Save salaros/6e026790b5e94aa955b7502727a375bb to your computer and use it in GitHub Desktop.
Save salaros/6e026790b5e94aa955b7502727a375bb to your computer and use it in GitHub Desktop.
In absence of Microsoft.Extensions.Localization and Microsoft.Extensions.DependencyInjection on .NET Framework < 4.6.1 (4.0, 4.5, 4.6) this class provides an easy access to localized resources
/// <summary>
/// In absence of <see cref="T:Microsoft.Extensions.Localization"/> and <see cref="T:Microsoft.Extensions.DependencyInjection"/>
/// on .NET Framework &lt; 4.6.1 this class provides an easy access to localized resources
/// </summary>
/// <seealso cref="IDisposable" />
/// <inheritdoc />
public class StringLocalizer : IDisposable
{
protected ResourceManager resourceManager;
/// <summary>
/// Initializes a new instance of the <see cref="StringLocalizer" /> class.
/// </summary>
/// <param name="assembly">The assembly containing localized string resources.</param>
/// <param name="resourceLocation">The resource location, defaults to 'Properties.Resources'.</param>
public StringLocalizer(Assembly assembly = null, string resourceLocation = "Properties.Resources")
{
var callingAssembly = assembly ??
new StackTrace().GetFrame(1).GetMethod()?.ReflectedType?.Assembly ??
Assembly.GetEntryAssembly();
var rootNameSpace = callingAssembly.ManifestModule.GetTypes().Min(t => t.Namespace);
resourceManager = new ResourceManager($"{rootNameSpace}.{resourceLocation}", callingAssembly);
}
/// <summary>
/// Finalizes an instance of the <see cref="StringLocalizer" /> class.
/// </summary>
~StringLocalizer()
{
ReleaseUnmanagedResources();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <inheritdoc />
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources.
/// </summary>
private void ReleaseUnmanagedResources()
{
resourceManager?.ReleaseAllResources();
}
/// <summary>
/// Gets the <see cref="System.String"/> with the specified string.
/// </summary>
/// <value>
/// The <see cref="System.String"/>.
/// </value>
/// <param name="str">The string.</param>
/// <returns></returns>
public string this[string str]
{
get
{
try
{
return resourceManager.GetString(str);
}
catch
{
return str;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment