Web API with Unity IOC - How is my DBContext Dependecy resolved?

I need help understanding unity and how IOC works.

I have it in my UnityContainer

var container = new UnityContainer(); // Register types container.RegisterType<IService, Service>(new HierarchicalLifetimeManager()); config.DependencyResolver = new UnityResolver(container); 

Then in my web API controller, I understand that IService is introduced by Unity because it is a registered type.

 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); } } 

My service interface

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

My implementation service has its own constructor that accepts an EntityFramework DBContext object. (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); } } 
+5
source share
1 answer

The reason it works is because MyDbContext has a constructor without parameters (or has a constructor containing parameters that can be resolved by a unit), and since unity by default can resolve specific types without registering.

Quote from this link :

If you try to resolve a specific class without matching, which does not have the appropriate registration in the container, Unity will instantiate this class and fill in any dependencies.

You also need to understand the concept of automatic wiring.

When the container tries to enable MyController , it discovers that it needs to allow the IService , which maps to Service . When the container tries to allow Service , it discovers that it needs to allow MyDbContext . This process is called automatic posting and is performed recursively until the entire graph of the object is created.

+2
source

All Articles