【发布时间】:2010-07-22 22:14:55
【问题描述】:
我正在尝试将两个具体类绑定到一个接口。我应该在 Ninject 中使用什么命令来做到这一点?我要做的是基于控制器名称将两个具体类绑定到一个接口。那可能吗?我想在 ninject 中你使用 .When 给出条件,但没有教程向你展示如何使用 .When 进行 ninject。
【问题讨论】:
标签: asp.net-mvc dependency-injection ninject
我正在尝试将两个具体类绑定到一个接口。我应该在 Ninject 中使用什么命令来做到这一点?我要做的是基于控制器名称将两个具体类绑定到一个接口。那可能吗?我想在 ninject 中你使用 .When 给出条件,但没有教程向你展示如何使用 .When 进行 ninject。
【问题讨论】:
标签: asp.net-mvc dependency-injection ninject
这里有几个例子。查看 Ninject 源项目及其 Tests 子项目以了解各种使用示例,这是最好的文档,尤其是因为文档尚未针对 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
【讨论】: