Search code examples
ninjectninject-extensions

Ninject ActivationException on ChildKernel


I'm getting an ActivationException saying there was an error activating IEventBroker. MyDataSource takes an IEventBroker has a parameter. If I don't use the child kernel, there is no issue. What is going on?

        var kernel = new StandardKernel();
        var childKernel = new ChildKernel(kernel);
        var eventBroker = new EventBroker();
        childKernel.Bind<IEventBroker>().ToConstant(eventBroker);         
        var myDS = childKernel.Get<MyDataSource>();

Solution

  • From the ChildKernel readme:

    The default behavior of Ninject that classes are bound to themself if not explicit still exists. But in this case this will be done by the top most parent. This means that this class can not have any dependency defined on a child kernel. I strongly suggest to have a binding for all objects that are resolved by ninject and not to use this default behavior.

    So you need to explicitly bind MyDataSource to self to make it work:

    var kernel = new StandardKernel();
    var childKernel = new ChildKernel(kernel);
    var eventBroker = new EventBroker();
    childKernel.Bind<IEventBroker>().ToConstant(eventBroker);
    childKernel.Bind<MyDataSource>().ToSelf();
    var myDS = childKernel.Get<MyDataSource>();