我是否可以编写 Unity 扩展以获得将依赖项属性应用于所有公共属性的效果

本文关键字:属性 应用于 是否 Unity 扩展 依赖 | 更新日期: 2023-09-27 18:31:01

我认为这应该很容易,但我不知道这样做的确切机制(见问题标题)。

它的工作方式可能是这样的:

[AutoInjectProperties]
public class C
{
  public class C(bool b)
  {
    if(b)
    {
      this.MyClass3 = new MyClass3(); // prevents auto inject
    }
  }
  public MyClass1 { get; set; } // auto inject
  public MyClass2 { get; }
  public MyClass3 { get; set; } // auto inject if null after construction
}

我是否可以编写 Unity 扩展以获得将依赖项属性应用于所有公共属性的效果

我根本不会使用DependencyAttribute。这不是建议的做法。请改用DependencyProperty

container.RegisterType<IMyInterface, MyImplementation>(new DependencyProperty("Foo"));
如果要注入的

依赖项是必需的,则应使用构造函数注入而不是属性注入。Unity 自行计算出构造函数参数。

public class MyImplementation
{
  private readonly IFoo foo;
  public MyImplementation(IFoo foo)
  {
    if(foo == null) throw new ArgumentNullException("foo");
    this.foo = foo;
  }
  public IFoo Foo { get { return this.foo; } }
}

如果您在解析之前注册IFoo MyImplementation Unity 将完成其工作并为您注入。


更新

public class AllProperties : InjectionMember
{
  private readonly List<InjectionProperty> properties;
  public AllProperties()
  {
    this.properties = new List<InjectionProperty>();
  }
  public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
  {
    if(implementationType == null)throw new ArgumentNullException("implementationType");
    // get all properties that have a setter and are not indexers
    var settableProperties = implementationType
      .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
      .Where(pi => pi.CanWrite && pi.GetSetMethod(false) != null && pi.GetIndexParameters().Length == 0);
    // let the Unity infrastructure do the heavy lifting for you
    foreach (PropertyInfo property in settableProperties)
    {
      this.properties.Add(new InjectionProperty(property.Name));
    }
    this.properties.ForEach(p => p.AddPolicies(serviceType, implementationType, name, policies));
  }
}

像这样使用它

container.RegisterType<Foo>(new AllProperties());

它将注入具有公共资源库的所有属性。