2

Web API 2コントローラも搭載したASP.MVC 4サイトがあります。 DIのためにUnity.MVCを使用しています。 javacriptからAPIを呼び出すと、コントローラーのインスタンスを作成できないというメッセージが表示されます。デフォルトのctorを作成するとインスタンスが作成されますが、依存関係はnullですが、少なくともその部分が動作していることはわかります。ここでUnity.MVCはパラメータでコントローラコントローラを解決できません

は私のAPI CTORである:ここで

public class ContactController : ApiController 
    { 
     IContactService service; 

     // dependency injection is being done here by Unity. look in UnityConfig where we register IContactSevice to ContactService. Whenever asp.net see's IContactService it now knows to make a new ContactService instance 
     // we do this for 2 reasons: 1) this makes unit testing possible where we can mock the IContactService and 2) this makes maintaining the code easier where we can change the contact service class we want to use later and we wouldn't have to change the code here in this controller 
     public ContactController(IContactService _service) 
     { 
      service = _service; 
     } 

はUnityConfig.cs内にある(それは私がNuGetからそれを持って、私は依存関係を記入するときに私のために自動生成しました)。これは、私がアプリケーションを起動するときに呼び出されます。

public static void RegisterTypes(IUnityContainer container) 
     { 
      container.RegisterType<IContactService, ContactService>(); 
     } 

何が欠けていますか?

+0

WebAPIコントローラには、個別のUnity登録があります。 _Unity.MVC_を使用しているのを見て、_Unity.AspNet.WebApi_ブートストラップもあります。 – Jasen

+0

ああ、私は参照してください。興味深いことに、これを追加するとUnityConfig.csも作成されます(この場合は上書きされます)。私は2つのプロジェクトを混在させることができますか? – user441521

+0

あなたは両方を持つことができます。私はあなたが2番目のパッケージをインポートする前に別々にファイルを保存し、次に2つを手動で組み合わせなければならないと思います。 – Jasen

答えて

2

WebAPIコントローラには、個別のUnity登録があります。すでにUnity.MVCパッケージを使用しているので、Unity.AspNet.WebApiブートストラップを追加できます。

コンフィギュレーションは自動的に置き換えられるので、2番目のパッケージをインポートする前にUnityConfig.csの内容を保存してから手動で組み合わせます。しかし、実際の違いは別々です。Unity * Activator.csファイル。

関連する問題