gpt4 book ai didi

ninject - Ninject 2 中的上下文变量

转载 作者:行者123 更新时间:2023-12-02 11:10:02 31 4
gpt4 key购买 nike

我找到了this article关于 Ninject 早期版本中的上下文变量。我的问题有两个方面。首先,如何使用 Ninject 2 获得这种行为?其次,上下文变量是否沿着请求链传递?例如,假设我想替换这些调用:

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

...这样:

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

是否可以设置这样的绑定(bind),当构建 C 时,上下文会记住它处于“特殊”上下文中?

最佳答案

这是我在 V2 上使用的一些东西,我花了大约 0 的努力为您清理它 - 如果您无法解决它,请告诉我。

正如您所猜测的,似乎没有一个真正明确的 API 可以按原样显示 v2 中的“上下文参数,即使是嵌套解析”内容(它的存在被隐藏为重载中的第三个参数) 参数 ctor)。

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 );
}
}

这里有一些代码[这会让事情变得困惑],它演示了我如何在我的上下文中应用它:-

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 ) );
}
}

像往常一样,您应该查看源代码和测试 - 他们将为您提供比我更详细和相关的答案。

关于ninject - Ninject 2 中的上下文变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3978909/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com