'Asp.Net Core - Access IStringLocalizer instance form static class
Is there better way to inject IStringLocalizer
object into static class so that I would not use method injection and pass localizer instance from view to the extension method each time?
Here's my view code
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@Html.GetString("some key", Localizer)
....
and extension method itself:
public static class Extensions
{
public static string GetString (this IHtmlHelper helper, string key, IViewLocalizer localizer)
{
return localizer[key]
}
}
Solution 1:[1]
Because of the static nature of the code being accessed, a service locator approach would need to be applied.
Resolve the desired type via the IHtmlHelper.ViewContext
public static class Extensions {
public static string GetString (this IHtmlHelper helper, string key) {
IServiceProvider services = helper.ViewContext.HttpContext.RequestServices;
IViewLocalizer localizer = services.GetRequiredService<IViewLocalizer>();
return localizer[key]
}
}
Which allows it to be used in the view
@Html.GetString("some key")
Solution 2:[2]
I using
- controler
viewbag = _localizer
- view
FilterDynamic.CustomeFieldDynamic(conditionTypeParam, ViewBag.test);
- class static
public static List<FieldTypeModel> CustomeFieldDynamic(int controlType, IJsonStringLocalizer localizer)
Solution 3:[3]
I came across this result and wanted to pass on my own implementation as none of the previous answers helped me with my case.
This solution doesn't use HtmlHelper in the method though. You can change IStringLocalizer to IViewLocalizer. It is implemented on handling enums localization, but you get the thrill.
public static string GetEnumString<T>(this IStringLocalizer<TRes> localizer, T _enum) where T : Enum
{
var type = _enum.GetType();
var typeString = type.Name;
var valueString = _enum.ToString();
return localizer[$"{typeString}_{valueString}"];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nkosi |
Solution 2 | Huy Bùi Kh?c |
Solution 3 | Mika Rissanen |