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);
}
}
おそらく 'MyDbContext'にはパラメータのないコンストラクタがあります。 Unityは登録せずに具体的なクラスを解決できます。 –