Skip to content

ContextPreservingGet

bartelink edited this page Mar 22, 2013 · 2 revisions

Scenario

There are situations where you Bind an interface To a Method that uses the Kernel to resolve a service in a specific manner, e.g. if you have a Service with several interfaces.

public class Service : IServiceA, IServiceB {}
 
Bind<Service>().ToSelf().InSingletonScope()
Bind<IServiceA>().ToMethod(ctx => ctx.Kernel.Get<Service>());
Bind<IServiceB>().ToMethod(ctx => ctx.Kernel.Get<Service>());

The problem

With the Bindings as above, the contextual information regarding which interface is being Resolved is lost. This means you can not apply Conditional Bindings in a meaningful manner. A further problem is that if the binding fails, the Ninject resolution trace within the exception's Message will only be for the innermost request. The Context Preservation Extension provides the ContextPreservingGet() extension method to address these two concerns.

Apply ContextPreservingGet instead of Get

public class Service : IServiceA, IServiceB {}
 
Bind<Service>().ToSelf().InSingletonScope();
Bind<IServiceA>().ToMethod(ctx => ctx.ContextPreservingGet<Service>());
Bind<IServiceB>().ToMethod(ctx => ctx.ContextPreservingGet<Service>());

Using the above, the ParentRequest will be maintained correctly in order to use in other Bindings and any resolution issues will include the complete trace.

Nitpicker's corner

Yes, it is indeed true that, as of version 3 there are new Bind overloads that allow one to natively achieve the dual binding being accomplished above, but don't let that stop you understanding the facility with a simple example!