Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting DI service on a extension method

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;
    }
}
like image 302
Tiago Avatar asked Feb 14 '17 20:02

Tiago


People also ask

How do you implement DI?

The recommended way to implement DI is, you should use DI containers. If you compose an application without a DI CONTAINER, it is like a POOR MAN'S DI . If you want to implement DI within your ASP.NET MVC application using a DI container, please do refer to Dependency Injection in ASP.NET MVC using Unity IoC Container.

What is dependency injection example?

What is dependency injection? Classes often require references to other classes. For example, a Car class might need a reference to an Engine class. These required classes are called dependencies, and in this example the Car class is dependent on having an instance of the Engine class to run.


2 Answers

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

like image 50
Tiago Avatar answered Oct 22 '22 15:10

Tiago


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.

like image 23
Henk Mollema Avatar answered Oct 22 '22 16:10

Henk Mollema