13

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;
    }
}
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
Tiago
  • 2,871
  • 4
  • 23
  • 39
  • 1
    There are some ugly tricks that could work https://github.com/aspnet/DependencyInjection/issues/294 – Matjaž Feb 14 '17 at 22:13
  • 13
    I would argue that your extension method should be a service of its own (`ITypeNameLocalizer`) because it has a dependency. Reserve extension methods *only* for simple logic that is unlikely to change and will never have dependencies. – NightOwl888 Feb 14 '17 at 23:06
  • +10 for @NightOwl888. – Steven Feb 15 '17 at 08:49
  • Note if you want to use DI in an HTML helper, you could do something like in [this answer](https://stackoverflow.com/a/44321214/). – NightOwl888 Feb 03 '18 at 16:16

2 Answers2

6

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

Community
  • 1
  • 1
Tiago
  • 2,871
  • 4
  • 23
  • 39
5

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.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
  • 5
    because you will need to pass the interface as a parameter wherever you want to use the extension method. – CageE Nov 19 '19 at 16:50