2011-05-29 79 views
4

我想了解Ninject上下文綁定。我瞭解在設計時知道我的背景的場景。例如我知道我可以使用命名屬性將DB對象綁定到模擬數據庫,當我想在測試類和SQL DB中使用它時,從我的實際代碼中使用它。運行時Ninject上下文綁定

但是,我不知道如何在運行時處理上下文綁定。例如假設我正在爲購物中心編寫軟件。店主可以使用keyboad進行計費或使用條形碼掃描儀。我不知道他會事先使用哪一個。他可能會在未來增加其他掃描方式,如RFID。

因此,我有以下幾點:

interface IInputDevice 
{ 
    public void PerformInput(); 
} 

class KeyboardInput : IInputDevice 
{ 
    public void PerformInput() 
    { 
     Console.Writeline("Keyboard");  
    } 
} 

class BarcodeInput : IInputDevice 
{ 
    public void PerformInput() 
    { 
     Console.Writeline("Barcode");    
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     IKernel kernel = new StandardKernel(new TestModule()); 

     var inputDevice = kernel.Get<IInputDevice>(); 

     inputDevice.PerformInput(); 

     Console.ReadLine(); 
    } 
} 

public class TestModule : Ninject.Modules.NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<IInputDevice>().To<....>(); 
    } 
} 

所以,我怎麼能去了解它的自定義代碼量最少?我想要求特定的代碼示例,而不是鏈接到關於上下文綁定的文章/維基/教程。

回答

7

您將需要一些標準來決定使用哪一個。例如。 App.config或設備檢測。然後使用條件綁定:

Bind<IInputDevice>().To<KeyboardInput>().When(KeyboardIsConfigured); 
Bind<IInputDevice>().To<BarcodeInput>().When(BarcodeReaderIsConfigured); 

public bool KeyboardIsConfigured(IContext ctx) 
{ 
    // Some code to decide if the keyboard shall be used 
} 

public bool BarcodeReaderIsConfigured(IContext ctx) 
{ 
    // Some code to decide if the barcode reader shall be used 
}