Resolving an existing instance with Ninject

Today I was looking for a way to allow a type to resolve to a specific instance that I had already created – something not known at the time the Ninject kernel is initialised. There is no method of a Ninject binding that explicitly handles this kind of thing.

The trick is to use the ToMethod method. ToMethod takes a lamda as a parameter. It’s defined as:

ToMethod(Func<IContext, IInstance> method)

This means ToMethod takes a function that accepts the injection context and returns an instance of the type being bound to. We can now use this to return our specific instance:

myKernel.Bind<IMyInstance>.To(context => anInstanceOfMyInstance);

The gotcha being that any Get of IMyInstance will result in a reference to the original anInstanceOfMyInstance. You have to be careful of lifetime, and therefore scope, and any changes to state.

I’m not convinced that this is actually a good idea, but it solves my immediate problem.

NInjectExistingInstanceTest

(And yes, this represents yet another return to blogging in some more regular form… I do intend to come through with the previously promised goods, just not in any specific order…)