tags:

views:

152

answers:

1

I'm working on a framework extension which handles dynamic injection using Ninject as the IoC container, but I'm having some trouble trying to work out how to achieve this.

The expectation of my framework is that you'll pass in the IModule(s) so it can easily be used in MVC, WebForms, etc. So I have the class structured like this:

public class NinjectFactory : IFactory, IDisposable {
  readonly IKernel kernel;
  public NinjectFactory(IModule[] modules) {
    kernel = new StandardKernel(modules);
  }
}

This is fine, I can create an instance in a Unit Test and pass in a basic implementation of IModule (using the build in InlineModule which seems to be recommended for testing).

The problem is that it's not until runtime that I know the type(s) I need to inject, and they are requested through the framework I'm extending, in a method like this:

public IInterface Create(Type neededType) {

}

And here's where I'm stumped, I'm not sure the best way to check->create (if required)->return, I have this so far:

public IInterface Create(Type neededType) {
  if(!kernel.Components.Has(neededType)) {
    kernel.Components.Connect(neededType, new StandardBindingFactory());
  }
}

This adds it to the components collection, but I can't work out if it's created an instance or how I create an instance and pass in arguments for the .ctor.

Am I going about this the right way, or is Ninject not even meant to be be used that way?

+2  A: 

Unless you want to alter or extend the internals of Ninject, you don't need to add anything to the Components collection on the kernel. To determine if a binding is available for a type, you can do something like this:

Type neededType = ...;
IKernel kernel = ...;

var registry = kernel.Components.Get<IBindingRegistry>();
if (registry.Has(neededType)) {
  // Ninject can activate the type
}
Nate Kohari