Michael
Michael

Reputation: 45

ASPNET CORE Dependency Injection in an attribute class

I am trying to develop a DisplayName Attribute which has an interface for localization service, which is already registered at startup and working if injected in a constructor.

How can I get the localization service interface to be instantiated since I cant use a construction injection?

This is my code

public class MyDisplayNameAttribute : System.ComponentModel.DisplayNameAttribute
{
    private string _resourceValue = string.Empty;
    private ILocalizationService _localizationService;
    public MyDisplayNameAttribute(string resourceKey)
       : base(resourceKey)
    {
        ResourceKey = resourceKey;
    }

    public string ResourceKey { get; set; }

    public override string DisplayName
    {
        get
        {
            _resourceValue = _localizationService.GetLocaleString(ResourceKey);

            return _resourceValue;
        }
    }

    public string Name
    {
        get { return nameof(MyDisplayNameAttribute); }
    }
}

Thanks

Upvotes: 1

Views: 1489

Answers (2)

Ali Mahmoodi
Ali Mahmoodi

Reputation: 1194

I hope you could solve the problem, this is a very simple solution but as you knew it's an anti-pattern :

   public class LocalizedDisplayNameAttribute : DisplayNameAttribute
   {
        public LocalizedDisplayNameAttribute(string Name) : base(Name)
        {
        }
        public override string DisplayName
        {
            get
            {
                var _localizationService= new HttpContextAccessor().HttpContext.RequestServices.GetService<ILocalizationService>();
                return _localizationService.Get(base.DisplayNameValue).Result;
            }
        }
    }

I Hope it helps others at least ;)

Upvotes: 2

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

Dependency injection is working with invertion of control (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2). So framework controls your app and when instantiating your clsses injects dependencies requested via constructor.

Refer also here How to create a class without constructor parameter which has dependency injection

So I suspect that it is not possible to inject dependency without using constructor.

May be if you describe you intention there may be another good solution.

Upvotes: 0

Related Questions