views:

34

answers:

2

Hi, How do I find what class is currently bound to the abstract class with Ninject in the following example:

if(conditional)
  Bind<IProducts>().To<Products>();
else
  Bind<IProducts>().To<SqlProducts>();
Type currentType = 'Type based upon current binding of IProducts'

How can I get the value of currentType.

+1  A: 

Kernel.Resolve is the low level entrypoint into the resolution machinery that you seek - it doesnt go as far as instantiating the objects.

I suggest downloading the trunk including tests and you'll get examples that cover your exact scenario. Dont treat this as a throwaway commment - the tests are proper clean xUnit.net tests that are exemplary in terms of being short, focused and having good coverage.

You may also find Kernel.Get<T>().GetType()/Kernel.TryGet<T>().GetType() or Kernel.GetAll<T> to be of use, depending on your exact scenario - if you can expand on same, I can make this answer more specific (however all of these instantiate the object rather than let you query the bindings at a low level.

Ruben Bartelink
Thanks for your answer and added tips. This is really what I needed was the samples since I haven't found many examples other than for Mvc controllers.
Mike
+1  A: 
kernel.Get<IProducts>().GetType() 

gave me the correct type at runtime.

Mike
(Obv as soon as you get enough points, stuff like this should be logged as a comment, but then you knew that!). Just be careful that the call you are doing results in an instantiation of the class (assuming you're not using a scope within which an instance has already been created- as covered in [another answer only a few hours ago](http://stackoverflow.com/questions/3543565/ninject-is-binding-stuff-behind-my-back/3546032#3546032)). This may or may not be a problem for you.
Ruben Bartelink