5
我想綁定兩個具體類到一個接口。我應該在Ninject中使用什麼命令來執行此操作?我想要做的是將兩個具體類綁定到控制器名稱上的一個接口上。那可能嗎?我想,在ninject中你使用。當給出條件,但沒有教程在那裏,他們告訴你如何使用。當ninject。Ninject綁定到不同的控制器
我想綁定兩個具體類到一個接口。我應該在Ninject中使用什麼命令來執行此操作?我想要做的是將兩個具體類綁定到控制器名稱上的一個接口上。那可能嗎?我想,在ninject中你使用。當給出條件,但沒有教程在那裏,他們告訴你如何使用。當ninject。Ninject綁定到不同的控制器
這裏有幾個例子。查看Ninject源項目及其測試子項目的各種使用示例,這是最好的文檔,尤其是因爲文檔尚未針對v2進行更新。
// usage of WhenClassHas attribute
Bind<IRepository>().To<XmlDefaultRepository>().WhenClassHas<PageAttribute>().WithConstructorArgument("contentType", ContentType.Page);
// usage of WhenInjectedInto
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(ServicesController));
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(PageController)).WithConstructorArgument("contentType", ContentType.Page);
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(WidgetZoneController)).WithConstructorArgument("contentType", ContentType.WidgetZone);
// you can also do this
Bind<IRepository>().To<PageRepository>().WhenInjectedInto(typeof(PageController)).WithConstructorArgument("contentType", ContentType.Page);
Bind<IRepository>().To<WidgetZoneRepository>().WhenInjectedInto(typeof(WidgetZoneController)).WithConstructorArgument("contentType", ContentType.WidgetZone);
// or this if you don't need any parameters to your constructor
Bind<IRepository>().To<PageRepository>().WhenInjectedInto(typeof(PageController));
Bind<IRepository>().To<WidgetZoneRepository>().WhenInjectedInto(typeof(WidgetZoneController));
// usage of ToMethod()
Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));
HTH
我嘗試WhenInjectedInto()命令,但仍然沒有爲我工作。如果你的控制器有參數,你真的需要添加WithConstructorArgument()嗎? – Ganator 2010-07-22 23:09:23
不,控制器只有一個構造函數接受IRepository,但是IRepository實現(在我的情況下是XmlDefaultRepository)具有構造函數,它接受string類型的contentType參數,這就是WithConstructorArgument()的例子。 – mare 2010-07-22 23:33:06
請注意 - 這些當...()和With ...()方法是可鏈接的時,您可以停在WhenInjectedInto()。而且,是的,只要您的Repository模式實現簡單,WhenInjectedInto()對我來說也是非常簡單的工作。您可以發佈您的存儲庫接口及其實現的代碼,並讓我們看看。還可以從設置DI的global.asax.cs中發佈代碼。 – mare 2010-07-22 23:35:27