-
Notifications
You must be signed in to change notification settings - Fork 7
ContextPreservingGet
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>());
With the Bind
ings 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.
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 Bind
ings and any resolution issues will include the complete trace.
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!