开发者

Late binding with Ninject

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?


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
}


Very very late answer but Microsoft.Practices.Unity allows Late Binding via App.Config

Just in case someone comes across this question

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜