利用Ninject實現依賴注入

來源:互聯網
上載者:User

與其手動費時費力地實現,不如利用Ninject方便的實現我們的需求。

Ninject如何將你需要的類型返回給你


拿前面的例子,士兵類:

 1 class Samurai  2 { 3     readonly IWeapon weapon; 4     public Samurai(IWeapon weapon)  5     { 6         this.weapon = weapon; 7     } 8  9     public void Attack(string target) 10     {11         this.weapon.Hit(target);12     }13 }

而Ninject希望這樣擷取具體計程車兵類:

IKernel kernel = new StandardKernel();var samurai = kernel.Get<Samurai>();

Ninject會利用建構函式擷取Samurai的執行個體,但Samurai的建構函式中包含一個IWeapon介面,而IWeapon介面是不可以執行個體化的。Ninject採用的方式是,typebinding,

typebinding是將具體的類和要實現的介面(抽象類別)進行綁定的技術。就這個例子來說,

Ninject會這樣實現:

1 Bind<IWeapon>().To<Sword>();

這句代碼的意思是,當Ninject碰到需要執行個體化IWeapon介面的時候,它會執行個體出Sword對象以滿足IWeapon的需要。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.