Ninject bind only when injected into IFactory.Create() method

173 Views Asked by At

I have a Foo class that derives from IFoo and then an IFooFactory that I setup via the Ninject Factory Extensions method:

Bind<IFooFactory>().ToFactory()

I then want to make sure any caller classes get an IFoo instance via IFooFactory.Create() rather than just ask for an IFoo in the constructor.

I have tried to create a binding like so:

Bind<IFoo>.To<Foo>
          .WhenInjectedInto<IFooFactory>();

Which I then later call fooFactory.Create() on. Unfortunately Ninject isn't happy with the binding and throws a "No matching bindings are available.." exception.

I am also running into the same issue when I have a Foo(string str) constructor whose string dependency is passed in to the factory method via IFooFactory.Create(string str).

1

There are 1 best solutions below

0
Andreas Appelros On

I looks like you are binding IFoo wrong. You have to do:

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

to make fooFactory.Create() know how to resolve IFoo. As it is now, IFoo will only get resolved when injected into IFooFactory, and that instance is autogenerated by the factory extension (I'm not even sure you can use WhenInjectedInto on interfaces).

If you only want to be able to resolve IFoo:s from the factory, you could use named bindings:

Bind<IFoo>().To<Foo>().Named("Foo");

The factory extension has a convention that if your factory method looks like this:

public interface IFooFactory 
{
    IFoo GetFoo();
}

it will use whatever follows "Get" as the name when resolving the binding. In this case "Foo".