Ninject 绑定到不同的控制器 [英] Ninject to bind on different controllers

查看:21
本文介绍了Ninject 绑定到不同的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将两个具体类绑定到一个接口.我应该在 Ninject 中使用什么命令来做到这一点?我想要做的是根据控制器名称将两个具体类绑定到一个接口.那可能吗?我想在 ninject 中你使用 .When 来给出条件,但没有教程告诉你如何使用 .When for ninject.

I am trying to Bind two concrete classes to one interface. What command should I use in Ninject to do that? What I am trying to do is to Bind two concrete classes to one interface base on the controller Name. Is that possible? I suppose that in ninject you use the .When to give the conditional but there is no tutorial out there where they show you how to use the .When for ninject.

推荐答案

这里有几个例子.查看 Ninject 源项目及其测试子项目以获取各种使用示例,这是最好的文档,尤其是因为文档尚未针对 v2 更新.

Here are few examples. Check out Ninject source project and its Tests subproject for various samples of usage, that's the best documentation for it, especially since docs haven't been updated for v2 yet.

// 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

这篇关于Ninject 绑定到不同的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆