1

2 つのクラスが同じ基礎となるインターフェイスの依存関係を持っているが、各クラス ctor のパラメーターの名前が異なるシナリオで、コンテキスト バインディングを管理する方法を理解するのに苦労しています。私の状況を示すための以下の疑似コード:

    interface IThing { }
    public class Thing1 : IThing { public Thing1(string fileCode) { } }
    public class Thing2 : IThing { public Thing2(string fileCode) { } }
    interface IThingFactory { IThing CreateThing(string fileCode); }

    interface IDependentThing { }
    public class A : IDependentThing { public A(string fileCode, IThingFactory thingFactory) { } }
    public class B : IDependentThing { public B(string fileCd, IThingFactory thingFactory) { } } //How to handle binding for this dependent?
    interface IDependentThingFactory { IDependentThing CreateDependentThing(string fileCode); }

    //...

    public override void Load()
    {
        Bind<IThing>().ToMethod(ctx =>
        {
            var fileCode = ctx.Parameters.First(p => p.Name == "fileCode").GetValue(ctx, null) as string;
            IThing thing = null;

            if (fileCode == "FileType1")
            {
                Bind<Thing1>().ToSelf().WithConstructorArgument("fileCode", fileCode);
                thing = Kernel.Get<Thing1>();
            }
            else if (fileCode == "FileType2")
            {
                Bind<Thing2>().ToSelf().WithConstructorArgument("fileCode", fileCode);
                thing = Kernel.Get<Thing2>();
            }
            return thing;
        });

        Bind<IThingFactory>().ToFactory();
        Bind<IDependentThingFactory>().ToFactory();
    }

//Later...
using (TextReader tr = new StreamReader(path))
{
    string firstLine = tr.ReadLine();

    if (firstLine.Substring(838, 1) == ".")
    {
        fileCode = "FileType1";
    }
    else if (firstLine.Substring(883, 1) == ".")
    {
        fileCode = "FileType2";
    }

    //won't work for creating B
    Kernel.Get<IDependentThing>(new ConstructorArgument("fileCode", fileCode));

    //or maybe...

    //seems to eliminate my problem by allowing me to handle variations
    //in parameter names  from within A and B's ctors, but looks like it
    //requires injecting factories along the chain (see A & B ctor arguments).
    dependentThingFactory.CreateDependentThing(fileCode) 
};

fileCodeは、ローカル ファイルの分析に基づいて計算されます。ファイルのタイプが決定されたら、そのファイルを処理するための適切なオブジェクトを Ninject に返してもらいたい

B定義した既存のバインディングには別の名前のコンストラクター パラメーターが必要なため、バインディングをどのように処理しますか? 一般的にこれを行うより良い方法はありますか?

を使えばいいと思いますp.Name == "fileCode" || p.Name == "fileCd"が、何か間違ったことをしているという感覚を揺るがすことはできません(面倒です)。また、名前でパラメーターを取得することにわくわくしていません。おそらく、Ninject に文字列パラメーターと比較してより具体的なものを一致させるカスタム型を作成することを考えました。私が立っているところから、複数のパラメーター名の状況を管理するか、文字列の代わりにパラメーターとしてカスタム型に切り替えるかのように見えます。

4

1 に答える 1