'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
Solution 1:[1]
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 ;)
Solution 2:[2]
Dependency injection is working with invertion of control (https://docs.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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Mahmoodi |
| Solution 2 | Fyodor |
