Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject get target type from IBinding

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.

like image 503
albertjan Avatar asked Apr 20 '12 08:04

albertjan


2 Answers

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));
}
like image 159
Schweder Avatar answered Oct 14 '22 19:10

Schweder


This is not possible. E.g what is the type In this case?

Bind<IX>().ToMethod(c => RandomBool() ? new Foo() : new Bar());
like image 3
Remo Gloor Avatar answered Oct 14 '22 19:10

Remo Gloor