2013-11-23 57 views
0

註冊到特定類型是什麼類型,我想爲不同的勇士如何指定我需要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"));

我該怎麼做?

+0

是你正在試圖做的實際使用情況怎樣?我發現這些類型的例子相當有問題,因爲它們不適用於使用依賴注入的現實場景。因此,解釋DI沒有很好的例子。請嘗試使用您正在嘗試構建的實際應用程序的概念,例如「ILoanCalculator」或「ICustomerRepository」。 – Steven

+0

在現實世界中,我想爲不同的存儲庫定義不同的數據庫(我爲不同的數據類型使用多個數據源)。像'builder.RegisterType ()。As ()。其中​​(t => t.Name.Contains(「someName」));''和'builder.RegisterType >()其中(T => t.Name.Not.Contains( 「someName」));' – user809808

回答

1

我要定義不同的存儲庫(我使用更多 比一個數據源的不同數據類型)不同的數據庫。像 builder.RegisterType()。As()。其中​​(t => t.Name .Contains(「someName」)); and builder.RegisterType()。As()。Where(t => t.Nam e.Not.Contains(「someName」));

消除設計中的歧義可能會更好。您的IDbDataContext含糊不清,因爲FirstDbDataContextSecondDbDataContext並不是真正的兼容性實現,因爲它們不可互換;版本庫需要某個數據庫,並且在傳入錯誤數據庫的IDbDataContext時它會失敗。

嘗試給每個上下文自己的抽象,如IFirstDbDataContextISecondDbDataContext。通過讓存儲庫明確地依賴於這兩個接口之一,任何查看構造函數的人都清楚這個存儲庫依賴於什麼。

但是,對於維護代碼的人來說,它不僅變得容易得多,使用DI容器將所有東西連接在一起變得非常容易,只是因爲您消除了歧義。

這是你結了註冊號:

builder.RegisterType<FirstDbDataContext>().As<IFirstDbDataContext>(); 
builder.RegisterType<SecondDbDataContext>().As<ISecondDbDataContext>(); 
相關問題