Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle 'deep' dependencies with IoC and DI?

I am new to IoC and I am playing with Unity. Let' say you have a solution with 'n' projects and you want to use Unity to register and resolve the dependencies. Lets say your composition root is in project a. Let's say you have the following projects in the solution.

a b c d

Lets say a depends on something in b, b depends on something in c and c depends on something in d

I have seen how you can use constructor injection to resolve the a => b dependency but I am stuck on how b's dependency on c can be resolved without access to the container that was configured and created in project a.

What is the approach for resolving the nested dependencies? Is there a discussion/blog/example addressing the resolution of deep dependencies?

like image 204
jparram Avatar asked Nov 11 '10 16:11

jparram


People also ask

Is DI and IoC both are same?

Dependency Injection is the method of providing the dependencies and Inversion of Control is the end result of Dependency Injection. IoC is a design principle where the control flow of the program is inverted.

What is DI or IoC?

Inversion of Control(IoC) is also known as Dependency injection (DI). The Spring container uses Dependency Injection (DI) to manage the components that build up an application and these objects are called Spring Beans. Spring implements DI by either an XML configuration file or annotations.

What is DI and IoC explain with an example?

Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application.

What is dependency injection What are the benefits of using an IoC container?

A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.


1 Answers

Your composition root should create and deliver all your dependencies, including nested ones, so it needs references to all the relevant assemblies (unless you're supplying them using reflection).

For example, you normally create an instance of B (supplying its dependency, C) before creating an A. If you did it 'by hand', it would look like this:

C c = new C();
B b = new B(c);
A a = new A(b);

As long as you register all the appropriate types, your dependency injection framework will resolve them for you.

For a great article on the subject, see Miško Hevery's "Dependency Injection Myth: Reference Passing."

like image 126
Jeff Sternal Avatar answered Sep 23 '22 07:09

Jeff Sternal