Context Variables in Ninject 2

I found this article about context variables in an earlier version of Ninject. My question is double. First, how can I get this behavior with Ninject 2? Second, do context variables execute along the request chain? For example, let's say I wanted to replace these calls:

var a = new A(new B(new C()))); var specialA = new A(new B(new SpecialC())); 

... with this:

 var a = kernel.Get<A>(); var specialA = kernel.Get<A>(With.Parameters.ContextVariable("special", "true")); 

Is it possible to establish a binding in which the context remembers that it is in a “special” context when the time comes to build C ?

+4
source share
1 answer

Here are some things that I use against V2, with an effort of ~ 0, to clear it for you - let me know if you can separate it.

As you guessed, there is no really explicit API that imposes a “context parameter, even for nested permissions” in v2 as-is (its presence is similar to the third parameter when Parameter ctor is overloaded).

 public static class ContextParameter { public static Parameter Create<T>( T value ) { return new Parameter( value.GetType().FullName, value, true ); } } public static class ContextParameterFacts { public class ProductId { public ProductId( string productId2 ) { Value = productId2; } public string Value { get; set; } } public class Repository { public Repository( ProductId productId ) { ProductId = productId; } public ProductId ProductId { get; set; } } public class Outer { public Outer( Repository repository ) { Repository = repository; } public Repository Repository { get; set; } } public class Module : NinjectModule { public override void Load() { Bind<ProductId>().ToContextParameter(); } } //[ Fact ] public static void TwoDeepShouldResolve() { var k = new StandardKernel( new Module() ); var o = k.Get<Outer>( ContextParameter.Create( new ProductId( "a" ) ) ); Debug.Assert( "a" == o.Repository.ProductId.Value ); } } 

And here is some code [which will confuse the question] that demonstrates how I apply it in my context: -

 public class ServicesNinjectModule : NinjectModule { public override void Load() { Bind<ProductId>().ToContextParameter(); Bind<Func<ProductId, ResourceAllocator>>().ToConstant( ( productId ) => Kernel.Get<ResourceAllocator>( ContextParameter.Create( productId ) ) ); } } public static class NinjectContextParameterExtensions { public static IBindingWhenInNamedWithOrOnSyntax<T> ToContextParameter<T>( this IBindingToSyntax<T> bindingToSyntax ) { return bindingToSyntax.ToMethod( context => (T)context.Parameters.Single( parameter => parameter.Name == typeof( T ).FullName ).GetValue( context ) ); } } 

As usual, you should look at the source and tests - they will provide you with a much more detailed and relevant answer than I can.

+3
source

All Articles