Dominik Fretz
Dominik Fretz

Reputation: 1378

Extending Ninject bindings via conventions

I manually setup the Ninject (v3) bindings in my application via module:

public class FooBarModule : NinjectModule
{
    public override void Load()
    {
        Kernel.Bind<IFooBar>().To<FooBarOne>().InSingletonScope();
        Kernel.Bind<IFooBar>().To<FooBarTwo>().InSingletonScope();
    }
}

Now, some classes in my system implement the interface IBoostrapable:

public class FooBarOne : IFooBar, IBootstrapable 
{ ... }

I would like to automatically extend the Ninject bindings for the classes that implement this interface.

So, in the end I would like to be able to do:

var fooBars = Kernel.GetAll<IFooBar>();
var bootstrapbables = Kernel.GetAll<IBootstrapable>();
fooBars.Count().Should().Be(2); // Instance of FooBarOne and FooBarTwo
bootstrapbables.Count().Should().Be(1); // instance of FooBarOne

The important thing is, that I actually extends the existing binding (so keeps the singelton scope.

Can this be done with an extension point somehow?

Regards,

Dominik

Upvotes: 1

Views: 85

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

You can use conventions. E.g.

kernel.Bind(x => x
    .FromThisAssembly()
    .SelectAllClasses()
    .InheritedFrom<IFooBar>()
    .BindAllInterfaces()
    .Configure(c => c.InSingletonScope());

Upvotes: 2

Related Questions