I have an Interface that is implemented by several types. But before I do a kernel.GetAll<IAmServiceable>()
I want to be able to ponder the target types of the injection.
I know the function kernel.GetBindings(typeof(IAmServiceable))
exists but this returns a list of IBinding
's.
Does anyone know how I can get the target type from the IBinding
?
I want to know the type that is bound to IAmServiceable
before it gets instantiated.
I know it's probably a bit late now for your problem, but since i ran into this today, i thought others might too.
That's the code i finally came up with - i don't think its perfect (far from it), especially regarding performance, but it works for my case, and since i do not intend to call this method very often, it seems ok to me.
public Type GetBoundToType(IKernel kernel, Type boundType)
{
var binding = kernel.GetBindings(boundType).FirstOrDefault();
if (binding != null)
{
if (binding.Target != BindingTarget.Type && binding.Target != BindingTarget.Self)
{
// TODO: maybe the code below could work for other BindingTarget values, too, feelfree to try
throw new InvalidOperationException(string.Format("Cannot find the type to which {0} is bound to, because it is bound using a method, provider or constant ", boundType));
}
var req = kernel.CreateRequest(boundType, metadata => true, new IParameter[0], true, false);
var cache = kernel.Components.Get<ICache>();
var planner = kernel.Components.Get<IPlanner>();
var pipeline = kernel.Components.Get<IPipeline>();
var provider = binding.GetProvider(new Context(kernel, req, binding, cache, planner, pipeline));
return provider.Type;
}
if (boundType.IsClass && !boundType.IsAbstract)
{
return boundType;
}
throw new InvalidOperationException(string.Format("Cannot find the type to which {0} is bound to", boundType));
}
This is not possible. E.g what is the type In this case?
Bind<IX>().ToMethod(c => RandomBool() ? new Foo() : new Bar());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With