4

以前のバージョンの Ninject のコンテキスト変数に関するこの記事を見つけました。私の質問は 2 つあります。まず、Ninject 2 でこの動作を取得するにはどうすればよいですか? 第 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"));

このようなバインディングを設定することは可能Cですか?

4

1 に答える 1

3

これが私がV2に対して使用しているもので、あなたのためにそれをクリーンアップするための努力はほとんどありません-あなたがそれを解き放つことができないかどうか私に知らせてください。

ご想像のとおり、v2では「ネストされた解像度の場合でもコンテキストパラメーター」をそのまま表示する明示的なAPIはないようです(Parameterctorのオーバーロード時に3番目のパラメーターとして存在が埋め込まれます)。

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

いつものように、あなたはソースとテストを見に行くべきです-それらは私ができるよりはるかに詳細で関連性のある答えをあなたに提供します。

于 2010-10-20T17:26:50.913 に答える