2010-07-22 71 views
5

我想绑定两个具体类到一个接口。我应该在Ninject中使用什么命令来执行此操作?我想要做的是将两个具体类绑定到控制器名称上的一个接口上。那可能吗?我想,在ninject中你使用。当给出条件,但没有教程在那里,他们告诉你如何使用。当ninject。Ninject绑定到不同的控制器

回答

8

这里有几个例子。查看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

+0

我尝试WhenInjectedInto()命令,但仍然没有为我工作。如果你的控制器有参数,你真的需要添加WithConstructorArgument()吗? – Ganator 2010-07-22 23:09:23

+0

不,控制器只有一个构造函数接受IRepository,但是IRepository实现(在我的情况下是XmlDefaultRepository)具有构造函数,它接受string类型的contentType参数,这就是WithConstructorArgument()的例子。 – mare 2010-07-22 23:33:06

+0

请注意 - 这些当...()和With ...()方法是可链接的时,您可以停在WhenInjectedInto()。而且,是的,只要您的Repository模式实现简单,WhenInjectedInto()对我来说也是非常简单的工作。您可以发布您的存储库接口及其实现的代码,并让我们看看。还可以从设置DI的global.asax.cs中发布代码。 – mare 2010-07-22 23:35:27