23

以下が機能していないため、WithConstructorArgumentの私の理解はおそらく間違っています。

私にはサービスがあり、そのコンストラクターが複数のオブジェクトを取得しているMyServiceと、testEmailという文字列パラメーターを呼び出します。この文字列パラメーターに対して、次のNinjectバインディングを追加しました。

string testEmail = "test@example.com";
kernel.Bind<IMyService>().To<MyService>().WithConstructorArgument("testEmail", testEmail);

ただし、次のコード行を実行すると、例外が発生します。

var myService = kernel.Get<MyService>();

これが私が得る例外です:

文字列のアクティブ化中にエラーが発生しました一致するバインディングが利用できず、タイプは自己バインドできません。アクティベーションパス:
2)タイプMyServiceのコンストラクターのパラメーターtestEmailへの依存性文字列の挿入
1)MyServiceの要求

提案:
1)文字列のバインディングが定義されていることを確認してください。
2)バインディングがモジュールで定義されている場合は、モジュールがカーネルにロードされていることを確認してください。
3)誤って複数のカーネルを作成していないことを確認してください。
4)コンストラクター引数を使用している場合は、パラメーター名がコンストラクターのパラメーター名と一致していることを確認してください。
5)モジュールの自動ロードを使用している場合は、検索パスとフィルターが正しいことを確認してください。

私はここで何が間違っているのですか?

更新

MyServiceコンストラクターは次のとおりです。

[Ninject.Inject]
public MyService(IMyRepository myRepository, IMyEventService myEventService, 
                 IUnitOfWork unitOfWork, ILoggingService log,
         IEmailService emailService, IConfigurationManager config,
         HttpContextBase httpContext, string testEmail)
{
    this.myRepository = myRepository;
    this.myEventService = myEventService;
    this.unitOfWork = unitOfWork;
    this.log = log;
    this.emailService = emailService;
    this.config = config;
    this.httpContext = httpContext;
    this.testEmail = testEmail;
}

すべてのコンストラクターパラメータータイプに標準のバインディングがあります。'string'のみにバインディングがなく、HttpContextBaseには少し異なるバインディングがあります。

kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(new HttpContext(new MyHttpRequest("", "", "", null, new StringWriter()))));

MyHttpRequestは次のように定義されています。

public class MyHttpRequest : SimpleWorkerRequest
{
    public string UserHostAddress;
    public string RawUrl;

    public MyHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output)
    : base(appVirtualDir, appPhysicalDir, page, query, output)
    {
        this.UserHostAddress = "127.0.0.1";
        this.RawUrl = null;
    }
}
4

2 に答える 2

37

ステートメントで:

var myService = kernel.Get<MyService>();

解決を試みていますがMyServiceMyServiceタイプがカーネルに登録されていないため、Ninjectはそれを自己バインド型として扱います。

したがって、を使用WithConstructorArgumentして解決することはありません。"testEmail"これは、でのみ使用されるためBind<IMyService>()、例外が発生する理由です。

したがって、に登録MyServiceしている場合:

string testEmail = "test@example.com";
kernel.Bind<IMyService>().To<MyService>()
      .WithConstructorArgument("testEmail", testEmail);

次に、登録済みのインターフェイス(IMyService)を使用して解決する必要があります。

var myService = kernel.Get<IMyService>();
于 2012-11-20T16:41:22.703 に答える
2

nemesvは正しい応答を示しますが、同じエラーが発生し、解決策は/bin内の不正なDLLでした。古いDLLにまだ存在していたいくつかのクラスをリファクタリングし、削除/移動しました。解決策-古いDLLを削除します。

于 2016-07-19T18:57:54.523 に答える