属性类中的ASPNET CORE依赖注入

问题描述 投票:0回答:1

我正在尝试开发一个DisplayName属性,它具有本地化服务的接口,该接口已在启动时注册并在构造函数中注入时工作。

由于我不能使用构造注入,如何才能实现本地化服务接口?

这是我的代码

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); }
    }
}

谢谢

c# asp.net-core dependency-injection inversion-of-control
1个回答
0
投票

依赖注入与控制反转(https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2)一起使用。所以框架控制你的应用程序,并在实例化你的clsses注入通过构造函数请求的依赖项。

另请参阅How to create a class without constructor parameter which has dependency injection

所以我怀疑在不使用构造函数的情况下注入依赖是不可能的。

如果你描述你的意图可能会有另一个好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.