属性 注入不适用于 Prism Unity

Propery injection not working with Prism Unity

我们有一个使用 Prism (7.2.0.1422) 和 Unity 作为 DI 容器的 WPF 应用程序。我有以下 class 尝试使用 Unity 属性 注入

  public class LocalizedDescriptionAttribute : DescriptionAttribute
  {
    [Dependency]
    IStringResource _stringResource { get; set; }
    string _resourceKey;
    public LocalizedDescriptionAttribute(string resourceKey)
    {
        _resourceKey = resourceKey;
    }

    public override string Description
    {
        get
        {
            string description = _stringResource.GetString(_resourceKey);
            return string.IsNullOrWhiteSpace(description) ? string.Format("[[{ 0}]]", _resourceKey) : description;
         }
      }
  }

   _stringResource  is always null. I have registered the type as a singleton like this in RegisterTypes

     containerRegistry.RegisterSingleton<IStringResource, StringResource>();

任何人有任何想法。 谢谢

根据 class 的名称,我认为它是一个实际属性? Unity 不能注入任何东西,因为容器只能注入它自己创建的实例。

但是,您可以绕道使用属性代码中的容器:CommonServiceLocator。这是一个静态的 class,只有在必要时才使用它,这可能是少数情况下它是个好主意的情况之一。您可以使用它在运行时从容器中解析 IStringResource