Search code examples
ninject

How do I have Ninject execute a factory I define to create my object?


Can I have Ninject execute a factory I define in order to create, say, object B below?

One way I can think of is by changing Foo's API like so:

class Foo
{
  public Foo(Bar b) { }

  // change API to introduce a new ctor
  [Inject]
  public Foo(Func<Bar> func) { }
}

class Bar { }

Is there an API in-built in Ninject 3.2 that will let me do this?


Solution

  • You can do the following:

    Bind<Bar>().ToMethod(ctx => ... your factory code/call...);
    

    and then just inject a Bar into foo:

    class Foo
    {
        public Foo(Bar b) { }
    }
    

    If you need to control the time when to create the Bar - so if your code needs to call the factory specifically - you can use Ninject.Extensions.Factory. Inject a Func<Bar> barFactory into your Foo and use it to create an instance.