-
Notifications
You must be signed in to change notification settings - Fork 36
Factory interface
The recommended way to add factories is to define an interface containing one or several methods to create the required dependencies as shown by the next code snippet.
public class Foo
{
private IBarFactroy barFactroy;
public Foo(IBarFactory barFactory)
{
this.barFactory = barFactory;
}
public void Do()
{
var bar = this.barFactroy.CreateBar();
...
}
}
public interface IBarFactory
{
Bar CreateBar();
}
This interface is declared at the same place as the class that is using it. In the binding configuration it can now be bound using the new ToFactory() method. This tells Ninject that it shall automatically implement a factory class for the specified interface and inject a new instance of this factory into each object that request an instance of the factory interface.
kernel.Bind().ToFactory();
Sometimes it is necessary to pass some parameters to the new instance. This can be done very simply by adding those parameters to the factory method. The extension uses the convention that you have to use the same parameter names in the factory like you did in the constructor of the created object. The order of the parameters in the factory method and constructor do not have to match.
public class Foo
{
private IBarFactroy barFactroy;
public Foo(IBarFactory barFactory)
{
this.barFactory = barFactory;
}
public void Do(int x, int y)
{
var bar = this.barFactroy.CreateBar(x, y);
...
}
}
public interface IBarFactory
{
Bar CreateBar(int x, int y);
}
public class Bar
{
public Bar(int y, int x)
{
}
}
foo.Do(1, 2); // Creates a Bar instance with x = 1, y = 2
Behind the scenes Ninject will create a proxy that implements the specified factory interface and intercept all methods so that the proxy behaves like the following implementation of the factory interface:
public class BarFactory : IBarFactory
{
private IResolutionRoot resolutionRoot;
public BarFactory(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public Bar CreateBar(int y, int x)
{
return this.resolutionRoot.Get(
new ConstructorArgument("y", y),
new ConstructorArgument("x", x));
}
}