Binding Common Types in Ninject 3.0

I want Ninject to create bindings for all types within a specific assembly that implement a common interface without specifying them at run time. As if open generics work in Autofac.

Here is what I came up with ...

kernel.Bind(x => x.FromThisAssembly() .SelectAllClasses() .Where(t => t.IsAssignableFrom( typeof(ICommandHandler<>))) .BindAllInterfaces()); 

The method call below, I would expect an array of all types implementing ICommandHandler<T> , but it does not give anything ...

 public void Process<TCommand>(TCommand command) where TCommand : ICommand { var handlers = _kernel.GetAll<ICommandHandler<TCommand>>(); foreach(var handler in handlers) { handler.Handle(command); } } 

Is there an existing way to achieve this? Or do I need to collapse by myself using the conventions API?

This seems to be a fairly common pattern, and he wondered if this could be achieved without writing my own implementation.

+2
generics c # ioc-container ninject
Jul 28 '12 at 15:51
source share
1 answer

Your binding does nothing due to two problems:

  • IsAssignableFrom expects parameters in the reverse order. You specified

     SomeCommand x = new ICommand<>(); 
  • A private generic class is not assigned to an open generic type. Or in other words

     ICommand<> x = new SomeCommand(); 

    Incorrect code.

What would you like:

 kernel.Bind(x => x.FromThisAssembly() .SelectAllClasses().InheritedFrom(typeof(ICommandHandler<>)) .BindAllInterfaces()); 
+6
Jul 30 '12 at 8:32
source share



All Articles