Ninject to bind on different controllers

前端 未结 1 1752
猫巷女王i
猫巷女王i 2020-12-06 08:10

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 int

相关标签:
1条回答
  • 2020-12-06 08:20

    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

    0 讨论(0)
提交回复
热议问题