註冊到特定類型是什麼類型,我想爲不同的勇士如何指定我需要Autofac
public interface IWarrior
{
string Kill();
}
public interface IWeapon
{
string KillSound();
}
public class Zombie : IWarrior
{
private readonly IWeapon _weapon;
public Zombie(IWeapon weapon)
{
_weapon = weapon;
}
public string Kill()
{
return _weapon.KillSound();
}
}
public class Soldier : IWarrior
{
private readonly IWeapon _weapon;
public Soldier(IWeapon weapon)
{
_weapon = weapon;
}
public string Kill()
{
return _weapon.KillSound();
}
}
public class Gun : IWeapon
{
public string KillSound()
{
return "Pif-paf";
}
}
public class Teeth :IWeapon
{
public string KillSound()
{
return "Chew-chew-chew";
}
}
我想說明這樣的指定武器類型:
builder.RegisterType<Gun>().As<IWeapon>().Where(t => t.Name.Equals("Soldier"));
builder.RegisterType<Teeth>().As<IWeapon>().Where(t => t.Name.Equals("Zombie"));
我該怎麼做?
是你正在試圖做的實際使用情況怎樣?我發現這些類型的例子相當有問題,因爲它們不適用於使用依賴注入的現實場景。因此,解釋DI沒有很好的例子。請嘗試使用您正在嘗試構建的實際應用程序的概念,例如「ILoanCalculator」或「ICustomerRepository」。 – Steven
在現實世界中,我想爲不同的存儲庫定義不同的數據庫(我爲不同的數據類型使用多個數據源)。像'builder.RegisterType()。As ()。其中(t => t.Name.Contains(「someName」));''和'builder.RegisterType >()其中(T => t.Name.Not.Contains( 「someName」));' –
user809808