简体   繁体   中英

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]
    }
}

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")

I using

  • controler viewbag = _localizer
  • view FilterDynamic.CustomeFieldDynamic(conditionTypeParam, ViewBag.test);
  • class static public static List<FieldTypeModel> CustomeFieldDynamic(int controlType, IJsonStringLocalizer localizer)

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}"];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM