0

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.

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103

1 Answers1

1

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).

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
  • Thanks, this does look what I want, but under the hood it still requires that I keep matching parameter names under the hood. This feels horrible to me as it introduces a weird set of bugs. I'll look at restructuring my code not to require this. – Jeff Foster Oct 04 '12 at 10:38
  • Yes, you do also need acceptance test-level coverage of some nature but that goes for a lot of things. (You could go mad and write some Rube Goldberg contraption that locates all the `ToFactory()` calls and spiders through the interfaces and checks that a constructor exists etc. But if you're even considering that, read the @ploeh post on testing DI config.) – Ruben Bartelink Oct 04 '12 at 14:43
  • I would recommend having a look in the source and the tests to see if there's an extensibility hook that you might be able to use to create something a la [NamedLikeFactoryMethod](https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface%3A-Referencing-Named-Bindings) which perhaps uses some of the mechanisms of the `.ToConstructor` part of the `Bind` fluent sequence to do some verification? (The last sentence isnt supposed to make sense but might get you thinking) – Ruben Bartelink Oct 04 '12 at 14:45