Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scan for all implementations of a generic type with Ninject

Tags:

c#

ninject

We are using the domain events pattern and leaning on our IoC container to locate handlers for a particular type of event:

public interface IHandleEvent<TEvent> where TEvent : IEvent
{
    void Handle(TEvent evnt);
}

With StructureMap we can scan and register all types implementing the above interface like so:

Scan(cfg =>
{
    cfg.TheCallingAssembly();
    cfg.ConnectImplementationsToTypesClosing(typeof(IHandleEvent<>));
});

Is there an equivalent with Ninject?

Currently I'm having to bind each handler individually like so:

kernel.Bind<IHandleEvent<SomeEvent>>().To<EventHandler1>();
kernel.Bind<IHandleEvent<SomeEvent>>().To<EventHandler2>();
kernel.Bind<IHandleEvent<SomeOtherEvent>>().To<EventHandler3>();
like image 908
Ben Foster Avatar asked Dec 18 '12 19:12

Ben Foster


2 Answers

The Ninject Conventions Extensions package did exactly what I need. The working code is below:

kernel.Bind(x => x
    .FromThisAssembly()
    .SelectAllClasses().InheritedFrom(typeof(IHandleEvent<>))
    .BindSingleInterface());
like image 139
Ben Foster Avatar answered Oct 19 '22 19:10

Ben Foster


Try Ninject Conventions Extensions. It provides a configuration by convention for Ninject. There is quite good documentation in wiki.

like image 5
mipe34 Avatar answered Oct 19 '22 17:10

mipe34