Ben Foster
Ben Foster

Reputation: 34800

How to scan for all implementations of a generic type with 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>();

Upvotes: 5

Views: 723

Answers (2)

Ben Foster
Ben Foster

Reputation: 34800

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

Upvotes: 7

mipe34
mipe34

Reputation: 5666

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

Upvotes: 5

Related Questions