我根本不会使用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());
它将注入所有具有公共设置器的属性。