views:

86

answers:

1

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.

A: 

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

mare
I try the WhenInjectedInto() command but still does not work for me. If your controller has parameters do you really need to add WithConstructorArgument()?
Ganator
No the controller only has a constructor that takes in IRepository, but the IRepository implementation (in my case XmlDefaultRepository) has the constructor that takes in contentType parameter of type string, that is what the example with WithConstructorArgument() is for.
mare
Please note - these When...() and With...() methods are chainable, you can stop at WhenInjectedInto(). And, yeah, WhenInjectedInto() does work for me out-of-the-box, very simple, provided that your Repository pattern implementation is simple too. You could post the code for your repository interface and its implementation and let us see. Also post code from global.asax.cs where you set up DI.
mare
yes thank you i got it now. i got them in the wrong way round. I should have put the WhenInjectedInto() Bind first before the general bind one. thanks.
Ganator