Mike
Mike

Reputation: 1425

Ninject convention based binding

Once again I think I might be missing the obvious here. I'm looking to do auto binding by conventions. I've been looking at the Ninject.extension.conventions project and the assembly scanner.

What I have is a lot lines that look like the following, that I would like to auto bind:

Bind<ICommandHandler<MyCommand>>().To<MyCommandHandler>();
Bind<ICommandHandler<MyOtherCommand>>().To<MyOtherCommandHander>();

I've tried several variations of:

Kernal.Scan(x => {
    x.FromAssemblyContaining<MyCommand>();
    x.WhereTypeInheritsFrom(typeof(ICommandHander<>));
    x.BindWith(new DefaultBindingGenerator());
});

But there are no instances returned when:

kernel.Get<ICommandHandler<T>>(); 

Upvotes: 4

Views: 3351

Answers (3)

Pete Montgomery
Pete Montgomery

Reputation: 4100

// use Ninject.Extensions.Conventions for convention-based binding
kernel.Scan(scanner =>
    {
        // look for types in this assembly
        scanner.FromCallingAssembly();

        // make ISomeType bind to SomeType by default (remove the 'I'!)
        scanner.BindWith<DefaultBindingGenerator>();
    });

Upvotes: 1

Mike
Mike

Reputation: 1425

The solution:

Kernel.Scan(x => {
    x.FromAssemblyContaining<CoreModule>();
     x.BindingGenerators.Add(new GenericBindingGenerator(typeof(IHandleQuery<,>)));
      x.InSingletonScope();
});

Upvotes: 0

Dave Thieben
Dave Thieben

Reputation: 5427

try looking at GenericBindingGenerator instead of DefaultBindingGenerator.

Upvotes: 4

Related Questions