Мне нужна помощь в понимании единства и как работает МОК.Web API с Unity IOC - Как разрешен мой DBContext Dependecy?
У меня есть это в моей UnityContainer
var container = new UnityContainer();
// Register types
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
Затем в моем веб-контроллера API, я понимаю, что IService впрыскивается единства, поскольку он был зарегистрирован тип.
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 может разрешать конкретные классы без регистрации. –