2
是否有可能爲所有實現接口註冊類型? E.g,我有一個:SimpleInjector - 爲所有接口註冊一個類型
public class Bow : IWeapon
{
#region IWeapon Members
public string Attack()
{
return "Shooted with a bow";
}
#endregion
}
public class HumanFighter
{
private readonly IWeapon weapon = null;
public HumanFighter(IWeapon weapon)
{
this.weapon = weapon;
}
public string Fight()
{
return this.weapon.Attack();
}
}
[Test]
public void Test2b()
{
Container container = new Container();
container.RegisterSingle<Bow>();
container.RegisterSingle<HumanFighter>();
// this would match the IWeapon to the Bow, as it
// is implemented by Bow
var humanFighter1 = container.GetInstance<HumanFighter>();
string s = humanFighter1.Fight();
}
我想這樣做自動接線使用的組件 - 我可以通過反射來完成,但是有什麼可以自動註冊一個類型並自動將它連接到它的所有實現接口? –
通用類型支持批量註冊,但不支持非通用接口。這是一個有意的設計決定。您可以詳細瞭解[這裏](http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Batch_Registration)。它會告訴你爲什麼它不被支持,以及如何使用反射來做到這一點。如果您對此有任何疑問,請告訴我。我很樂意爲您提供幫助。 – Steven
我已經通過反射解決了它 - 但是我想知道是否可以在本地完成,就像你可以用其他一些Ioc容器一樣。再次,這不是一個大問題,可以通過反思輕鬆實現。 –