Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need help understanding Unity and how IOC works.

I have this 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 injected by Unity because it was 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 Service Implementation has its own constructor that takes 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);
        }
    }
like image 829
duyn9uyen Avatar asked Oct 30 '22 03:10

duyn9uyen


1 Answers

The reason it is working is that MyDbContext has a parameterless constructor (or it has a constructor that contains parameters that unity can resolve), and because unity by default can resolve concrete types without registration.

Quoting from this reference:

When you attempt to resolve a non-mapped concrete class that does not have a matching registration in the container, Unity will create an instance of that class and populate any dependencies.

You also need to understand the concept of auto-wiring.

When the container tries to resolve MyController, it detects that it needs to resolve IService which is mapped to Service. When the container tries to resolve Service, it detects that it needs to resolve MyDbContext. This process is called auto-wiring and is done recursively until the whole object graph is created.

like image 106
Yacoub Massad Avatar answered Nov 15 '22 06:11

Yacoub Massad