0

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

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

[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
}
4

1 回答 1

2

我根本不会使用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在解决之前注册, MyImplementationUnity 将完成它的工作并为您注入它。


更新

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

它将注入所有具有公共设置器的属性。

于 2012-04-12T07:35:18.687 回答