2016-05-25 11 views
5

UnityとIOCの仕組みを理解するのに助けが必要です。Unity IOCを使用したWeb API - DBContext Dependecyはどのように解決されましたか?

私は私のUnityContainerに

var container = new UnityContainer(); 

// Register types    
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());    

config.DependencyResolver = new UnityResolver(container); 

これを持っている。そして、私のウェブAPIコントローラで、私はそれが登録したタイプだったので、IServiceはUnityが注入されることを理解しています。

public class MyController : ApiController 
{ 
    private IService _service; 

    //------- Inject dependency - from Unity 'container.RegisterType' 
    public MyController(IService service) 
    { 
     _service = service; 
    } 

    [HttpGet] 
    public IHttpActionResult Get(int id) 
    { 
     var test = _service.GetItemById(id); 
     return Ok(test); 
    } 
} 

マイ・サービス・インタフェース

public interface IService 
    { 
     Item GetItemById(int id); 
    } 

私のサービスの実装は、EntityFramework DBContextオブジェクトを受け取り、独自のコンストラクタを持っています。 (EF6)

public class Service : IService 
    { 
     private MyDbContext db; 

     // --- how is this happening!? 
     public IService(MyDbContext context) 
     { 
      // Who is calling this constructor and how is 'context' a newed instance of the DBContext? 
      db = context; 
     } 

     public Item GetItemById(int id) 
     { 
      // How is this working and db isn't null? 
      return db.Items.FirstOrDefault(x => x.EntityId == id); 
     } 
    } 
+0

おそらく 'MyDbContext'にはパラメータのないコンストラクタがあります。 Unityは登録せずに具体的なクラスを解決できます。 –

答えて

2

は、それが働いている理由は、MyDbContextは、パラメータなしのコンストラクタを持つ(またはそれは団結を解決できるパラメータが含まれているコンストラクタを持っている)、およびデフォルトで団結登録なし、コンクリートの型を解決することができますので、ということです。

this referenceからの引用:

あなたは、コンテナ内の一致する登録を持たない非マッピングされた具象クラスを解決しようとすると、Unityは、そのクラスのインスタンスを作成し、すべての依存関係を移入します。

また、自動配線の概念を理解する必要があります。

コンテナがMyControllerを解決しようとすると、ServiceにマップされたIServiceを解決する必要があることが検出されます。コンテナがServiceを解決しようとすると、MyDbContextを解決する必要があることが検出されます。このプロセスは自動配線と呼ばれ、オブジェクトグラフ全体が作成されるまで再帰的に実行されます。

+1

それはいくつかの狂った黒い魔法です!これは非常に明確な説明でした。ありがとうございました。 – duyn9uyen

+1

ようこそ。 [私の意見ではあまり良い魔法ではありません](http://criticalsoftwareblog.com/index.php/2015/08/23/why-di-containers-fail-with-complex-object-graphs/)。 –

関連する問題