Ninject Constructor Binding

605 Views Asked by At

I'm using NInject. I have an object like this

interface IFoo {}

class Foo : IFoo {
   public Foo(string magic, IBar bar) {}
}

I want to be able to inject some foo by passing only the magic. The magic is different for each class, so this should return different instances.

s_Kernel.Get<IFoo>("magic");
s_Kernel.Get<IFoo>("not-so-magic");

The first time I've tried to bind it I've done

s_Kernel.Bind<IFoo>().To<Foo>();

But then I have to look it up with something looks a bit naff.

s_Kernel.Get<IFoo>(new ConstructorArgument("magic", magic), s_Kernel.Get<IBar>());

I don't want to explicitly tie myself to the magic string.

I get the impression that Bind<IFoo>().ToConstructor(ctorArg => new Foo(xxx, ctorArg.Kernel.Get<IFoo>()); will almost get me there, but I don't know what I should put for "xxx" so that it looks up the argument.

1

There are 1 best solutions below

3
On BEST ANSWER

You're either looking for Ninject.Extensions.Factory (or the WithConstructorArgument piece at the very end of the Bind fluent-expression chain but I'm fairly sure you don't mean that).