【发布时间】:2016-05-25 14:45:01
【问题描述】:
我需要帮助来了解 Unity 以及 IOC 的工作原理。
我的 UnityContainer 中有这个
var container = new UnityContainer();
// Register types
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
然后在我的 Web 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 无需注册即可解析具体类。
标签: c# entity-framework asp.net-web-api unity-container