【问题标题】:Ninject to bind on different controllersNinject 绑定到不同的控制器
【发布时间】:2010-07-22 22:14:55
【问题描述】:

我正在尝试将两个具体类绑定到一个接口。我应该在 Ninject 中使用什么命令来做到这一点?我要做的是基于控制器名称将两个具体类绑定到一个接口。那可能吗?我想在 ninject 中你使用 .When 给出条件,但没有教程向你展示如何使用 .When 进行 ninject。

【问题讨论】:

    标签: asp.net-mvc dependency-injection ninject


    【解决方案1】:

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

    【讨论】:

    • 我尝试了 WhenInjectedInto() 命令,但对我仍然不起作用。如果你的控制器有参数,你真的需要添加 WithConstructorArgument() 吗?
    • 不,控制器只有一个接受 IRepository 的构造函数,但 IRepository 实现(在我的情况下为 XmlDefaultRepository)具有接受字符串类型的 contentType 参数的构造函数,这就是 WithConstructorArgument( ) 是为了。
    • 请注意 - 这些When...() 和With...() 方法是可链接的,您可以在WhenInjectedInto() 处停止。而且,是的,WhenInjectedInto() 对我来说是开箱即用的,非常简单,前提是您的存储库模式实现也很简单。您可以发布存储库接口及其实现的代码,让我们看看。还要从您设置 DI 的 global.asax.cs 中发布代码。
    • 是的,谢谢,我现在知道了。我把它们弄错了。我应该将 WhenInjectedInto() Bind 先放在一般绑定之前。谢谢。
    猜你喜欢
    • 2011-08-20
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多