Injecting DI service on a extension method

柔情痞子 提交于 2019-12-01 01:13:58

问题


I'm trying to get the IStringLocalizer service instance inside a extension method, is it possible? Any suggestions on how should I inject it?

My goal here is to translate a type using its name as convention.

public static class I18nExtensions
{

    private IStringLocalizer _localizer; // <<< How to inject it?

    public static string GetName(this Type type)
    {
        return _localizer[type.Name].Value;
    }
}

回答1:


Following @NightOwl888 comment I was in the wrong path, I ended up creating the following service:

public class TypeNameLocalizer : ITypeNameLocalizer
{
    private IStringLocalizer localizer;

    public TypeNameLocalizer(IStringLocalizer<Entities> localizer) 
    {
        this.localizer = localizer;
    }
    public string this[Type type] 
    { 
        get
        {
            return localizer[type.Name];
        }
    }
}

Credit: @NightOwl888




回答2:


Why not just pass the IStringLocalizer as a parameter:

public static string GetName(this Type type, IStringLocalizer localizer)
{
    return localizer[type.Name].Value;
}

The purpose of extension methods is to extend behavior of objects. It seems to me that is what you're trying to do here.



来源:https://stackoverflow.com/questions/42235948/injecting-di-service-on-a-extension-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!