Ninject get target type from IBinding

ninject dynamic binding
ninject rebind
ninject withconstructorargument
ninject kernel get
ninject constructor injection
ninject intransientscope
ninject documentation
ninject toconstant

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.

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

Bind<IX>().ToMethod(c => RandomBool() ? new Foo() : new Bar());

Contextual Binding · ninject/Ninject Wiki · GitHub, Get<T>() and there are multiple possible results for the given service type T ). At the target location, you indicate the name you want to use in the given binding metadata: extra information we include in a type binding  constraints on the type binding which take into account the target context Constraining the binding selection via ConstraintAttribute -derived attributes on the injection target ConstraintAttribute is an abstract attribute class from which one can derive your own constraints which filter the set of eligible bindings for injection into a target.

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));
}

Multi injection · ninject/Ninject Wiki · GitHub, Ninject allows you to inject multiple objects bound to a particular type or interface. public interface IWeapon { string Hit(string target); } public class Sword : IWeapon (The same applies to using Constructor Injection to get an How Injection Works · Contextual Binding · Conventions-Based Binding  /// The type must match one of the specified types exactly. Types that derive from one of the specified types Types that derive from one of the specified types /// will not be considered as valid target.

If you are working within a NinjectModule (or have access to an IKernel some other way) A nice simple approach would be:

var concreteType = Kernel.Get<InterfaceType>().GetType();

Obviously, the downside is you create an instance of the concrete type. It is nevertheless nice and simple and I think pretty robust. Obviously, if the interface derives from IDisposable you would use a using statement:

using(var obj = Kernel.Get<InterfaceType>())
{
    var concreteType = obj.GetType();
    .
    .
    .
}

NInject Cheat Sheet, A cheat sheet for Ninject IOC Frmaework in C# All source code can be found on GitHub here. ToProvider( ) // Binding with provider, class with parent of Target.Type ) ). Bind<IClass>().ToMethod( x => new ClassC(x.Kernel. C# (CSharp) Ninject.Planning.Bindings Binding - 9 examples found. These are the top rated real world C# (CSharp) examples of Ninject.Planning.Bindings.Binding extracted from open source projects. You can rate examples to help us improve the quality of examples.

HowTo – NInject – Part 2 – Advanced Features, Ninject Kernel uses different components to resolve types, and one of them is Binding information includes binding metadata and target information Oncethe matching binding isfound,it iseasyto get the concrete typefromthat binding. Building an IBindingResolver Component. Jump to bottom. The IBindingResolver interface is used by Ninject to locate bindings for resolution by the Kernel. It is primarily used to map the type requested to a similar type in the binding map. Given a type it returns a collection of bindings that can potentially satisfy that type.

Mastering Ninject for Dependency Injection, Bind(type).To(_cachedBindings[interfaceType]); } } } /// <summary> /// Resolves the closing interface. /// </summary> /// <param name="targetType">Type of the  With the list of bindings, we basically call kernel.Get(type) and verify that all of the dependencies are satisfied. So we do something similar to: So we do something similar to: Assert.DoesNotThrow(() => { var bindings = kernel.GetBindings(); foreach (var t in bindings) { kernel.Get(t); } });

Using NInject to bind a generic interface, with a default if a binding , Getting Started with Ninject To prepare Ninject for use, we need to create an instance Binding a Type to Ninject class Program { static void Main(string[] args​)  The T Get<T>(string key, T defaultValue) and void Set(string key, object value) methods have been removed from (I)NinjectSettings. The GetBindings(Type service) method in (I)KernelConfiguration, (I)ReadOnlyKernel and KernelBase now returns IBinding[] instead of IEnumerable<IBinding>.

Comments
  • Have you looked at using reflection to achieve the same thing? I'm not certain, but I think you can use it to find implemenations of a given interface within an assembly ...
  • Yes I did try that but it wont find a specific implementation of a generic class. GenericHostRunner<T> : IAmServicable which is bound in Ninject like: Bind<IAmServiceable>().To<GenericHostRunner<WCFHost>>() With reflection I'll only find GenericHostRunner.
  • But I just use Bind<IX>().To<Impl>(). :( Damn I was really hoping for a different answer.
  • I mean, I see that maybe this information isn't useful, but wouldn't the type be Func<IContext, IX>?