gpt4 book ai didi

asp.net-mvc - Ninject 绑定(bind)到不同的 Controller

转载 作者:行者123 更新时间:2023-12-02 00:34:26 25 4
gpt4 key购买 nike

我正在尝试将两个具体类绑定(bind)到一个接口(interface)。我应该在 Ninject 中使用什么命令来做到这一点?我想做的是将两个具体类绑定(bind)到一个基于 Controller 名称的接口(interface)。那可能吗?我想在 ninject 中,您使用 .When 给出条件,但没有教程向您展示如何使用 .When 进行 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

关于asp.net-mvc - Ninject 绑定(bind)到不同的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3313940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com