I've been playing with Ninject to see if it has the features I need to
port a project over to it. One feature that seemed missing was the
ability to bind to a factory method for a service. You can bind a
service to a factory method, but this is different. What I mean is
that a class can take as a dependency a factory method, where that
factory method can be any service already bound within that kernel.
So the class can create multiple instances of the dependency it has.
For example, a Juggler needs more than 1 weapon, they may need many
weapons over time. In fact every time they pull out a weapon, its a
new one, because presumably the old one was dropped.
public class Juggler : IWarrior
{
private readonly Func<IWeapon> _weaponFactory;
public Juggler(Func<IWeapon> weaponFactory)
{
_weaponFactory = weaponFactory;
}
public IWeapon Weapon
{
get { return _weaponFactory(); }
}
}
I'm not sure Ninject supports this natively, I couldn't find it.
Here's a test case. It passes, with the commit linked below. I'm
just sharing, and wondering if anyone else thinks this is useful or
perhaps has thoughts on a better approach.
class FactoryBindingTests : FactoryBindingContext
{
[Fact]
public void can_bind_factory()
{
kernel.Bind<IWeapon>().To<Sword>();
kernel.Bind<Juggler>().ToSelf();
var result = kernel.Get<Juggler>();
Assert.NotNull(result);
}
}
Commit adding this capability:
http://github.com/fschwiet/ninject/commit/1ae73369725b4378a178c379e2b65011bee68d58