Update
I’ve managed to get around this. Now I check myself, whether the dependency can be resolved. If not, I’ll look for a parameterless constructor (via Reflection) and call that. But I think this is Ninjects share of the work… so still more a workaround than a real solution.
Original Question
public class Test
{
public Test(INavigationService asd)
{
// rnd stuff
}
public Test()
{
// other rnd stuff
}
}
I’ve got this Test class. Now, I want two instances of it, created by Ninject. So I do the following:
Test test = Kernel.Get<Test>();
and run into an exception: “Ninject.ActivationException: Error activating INavigationService”.
If I reorder the constructors like this
public class Test
{
public Test()
{
// other rnd stuff
}
public Test(INavigationService asd)
{
// rnd stuff
}
}
it works.
But I can’t be sure, that every class I use with Ninject has its constructors in “correct” order.
So, is there a way to tell Ninject to not ignore the parameterless constructor, if it’s not the first one?
Thank you in advance.
Ninject tries to inject the one with the most parameters (that it knows how to resolve*). However, you can tell Ninject explicitly which
constructorto inject:Note: You cannot put
Injectattribute on more than one constructor. It’ll throw an exception.Update: Here’s another way to tackle this, worth trying.
Bind<ITest>().ToMethod(x => factoryMethod());factoryMethoddoes two things:Kernel.CanResolve()or some other way.ctor. If not, use the parameterless constructor.Feels tacky and not sure if this is a good pattern to follow. If the parameters are optional, a better thing to do is use property injection (frowned upon generally) or method injection maybe.