1
votes

Trying to do this with Ninject's factory extensions.

void Main()
{
    IKernel kernel = new StandardKernel();
    kernel.Bind<C>().ToMethod(ctx => new C());
    kernel.Bind<IBFactory>().ToFactory();
    var a = kernel.Get<A>();
    a.Do();
}
public class A
{
    IBFactory _fact;

    public A(IBFactory factory)
    {
        _fact = factory;
    }

    public void Do()
    {
        _fact.Get("blah").Dump();
    }
}

public class B
{
    public B(C c, string s)
    {
    }
}

public interface IBFactory
{
    B Get(string s);
}

public class C
{
}

The factory interface fails because it does not have a C to throw into the B() constructor. However it knows how to make a C from the kernel, but looking it up is beyond the scope of the default factory method implementation.

I can make a custom IInstanceProvider and pass that into the factory method e.g ToFactory(() => new myCustomIIProvider()) which resolves the C from the kernel, but it seems like a lot of work.

Is there an easier way to get Ninject to self resolve the missing ctor arg ?

1

1 Answers

0
votes

Actually, the problem isn't the binding for the C service, but the binding for B.

The default Factory instance provider will create named bindings for methods starting with Get (see here).

Either change your factory method to something other than Get or add this to create an empty named binding for B:

kernel.Bind<B>().ToSelf().Named("");