我需要帮助了解 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);
}
}
1 回答
它工作的原因是
MyDbContext
有一个无参数构造函数(或者它有一个包含 unity 可以解析的参数的构造函数),并且因为默认情况下 unity 可以在不注册的情况下解析具体类型。引用这个参考:
您还需要了解 auto-wiring 的概念。
当容器尝试解析
MyController
时,它会检测到它需要解析映射到Service
的IService
。当容器尝试解析Service
时,它会检测到它需要解析MyDbContext
。此过程称为 auto-wiring,并以递归方式完成,直到创建整个对象图。