Question

I have a WCF application that uses Ninject (along with the NinjectWebCommon file) to take care of my dependency injection needs for the most part (this is done at app start); however, I have a separate project in the same solution that where I would like to use the kernel to resolve some dependencies at run-time. How can I get access to my kernel in this "other" project? Is it even possible?

Was it helpful?

Solution

How can I get access to my kernel in this "other" project?

You shouldn't do this. Only the startup path of your application should reference the container/kernel. This part is called the Composition Root. The kernel shouldn't be referenced outside the Composition Root; that would be an application of the Service Locator anti-pattern, and would cause all sorts of maintainability issues.

The 'trick' here is to define an abstract factory interface in your application. You can implement this factory inside your composition root. This will keep the kernel references only inside the composition root and will therefore not result in the Service Locator anti-pattern.

For instance:

// Defined in a core layer of the application
public interface IItemProcessorFactory {
    IItemProcessor GetProcessor(ItemProcessorType type);
}

And inside your composition root (which could be a class or a namespace with multiple classes) you define an implementation:

// A nested type to exaggerate the fact that this is inside your Composition Root
private sealed class NinjectItemProcessorFactory : IItemProcessorFactory {
    private readonly Kernel kernel;
    public NinjectItemProcessorFactory(Kernel kernel) {
        this.kernel = kernel;
    }
    public IItemProcessor GetProcessor(ItemProcessorType type) {
        this.kernel.Get<IItemProcessor>(type.ToString());
    }
}

And the factory can be registered as follows:

kernel.Bind<IItemProcessorFactory>().To<NinjectItemProcessorFactory>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top