IoC Containers are also good for loading deeply nested class dependencies. For example if you had the following code using Depedency Injection.
public void GetPresenter()
{
var presenter = new CustomerPresenter(new CustomerService(new CustomerRepository(new DB())));
}
class CustomerPresenter
{
private readonly ICustomerService service;
public CustomerPresenter(ICustomerService service)
{
this.service = service;
}
}
class CustomerService
{
private readonly IRespository repository;
public CustomerService(IRespository repository)
{
this.repository = repository;
}
}
class CustomerRepository : IRespository
{
private readonly DB db;
public CustomerRepository(DB db)
{
this.db = db;
}
}
class DB { }
If you had all of these dependencies loaded into and IoC container you could Resolve the CustomerService and the all the child dependencies will automatically get resolved.
For example:
public static IoC
{
private IUnityContainer _container;
static IoC()
{
InitializeIoC();
}
static void InitializeIoC()
{
_container = new UnityContainer();
_container.RegisterType();
_container.RegisterType, CustomerRepository>();
}
static T Resolve()
{
return _container.Resolve();
}
}
public void GetPresenter()
{
var presenter = IoC.Resolve();
// presenter is loaded and all of its nested child dependencies
// are automatically injected
// -
// Also, note that only the Interfaces need to be registered
// the concrete types like DB and CustomerPresenter will automatically
// resolve.
}