2

私は次のクラスを持っています (私はそれらがうまく設計されていないことを知っています.Ninjectの問題を表現したいだけです).

コンストラクターの引数をサービスに渡す方法がわかりません (これは の依存Utility関係ですMainProgram):-

class MainProgram
{
    static IKernel kernel;
    static MainProgram mainProgram; 

    Utility Utility;

    static void Main(string[] args)
    {
        kernel = new StandardKernel(new DIModule());

        var constructorArgument1 = new ConstructorArgument("firstArg", args[0]);
        var constructorArgument2 = new ConstructorArgument("secondArg", args[1]);

        mainProgram = kernel.Get<MainProgram>(new IParameter[] { constructorArgument1, constructorArgument2 });
        mainProgram.Utility.ExportToXML();
    }


    public MainProgram(Utility utility)
    {
        this.utility = utility;
    }
}

public class Utility
{
    private IService service;
    public Utility(IService service)
    {
        this.service = service;
    }

    //methods to work with service
}

public class Service : IService 
{
    private readonly string firstArg;
    private readonly string secondArg;

    public Service(string firstArg, string secondArg)
    {
        this.firstArg = firstArg;
        this.secondArg = secondArg;
    }
}


class DIModule : NinjectModule
{
    public override void Load()
    {
        Bind<IService>().To<Service>();
        Bind<Utility>().ToSelf();
        Bind<MainProgram>().ToSelf();
    }
}

kernel.Get<MainProgram>()は次のメッセージで失敗します。

文字列の有効化中にエラーが発生しました

No matching bindings are available, and the type is not self-bindable.

これは、コンストラクターの引数が IService に到達していないためだと理解しています。

これは私の依存関係を解決するための正しいアプローチでもありますか? いくつかの場所で、kernel.Get() を使用すると「DI を使用していない」と読みました。

4

1 に答える 1

2

@Remo Gloor からのこのブログ投稿の「継承されたコンストラクター引数」を参照してください。ケースを機能させるには、 ctorのshouldInherit引数を渡す必要があります。ConstructorArgumenttrue

注意の言葉 - このような魔法のフローティング引数を持つことは、一般的には良い考えではありません - 何かを渡す必要がある場合は、それを渡し、コンテナのトリックを使用して問題を混乱させないでください (つまり、@Steven がコメントで述べたこと)。

(また、明らかにできればBind... WithConstructorArgument、それははるかに優れていますが、あなたはそれを知っていると思います。)

おそらく、抽象化が不足しています。簡単に逆方向に取得できる 2 つの文字列ではなく、1 つの文字列をService要求する必要があるのではないでしょうか?ServiceConfiguration

于 2013-04-23T09:57:24.100 に答える