Wednesday, 20 April 2016

What is IoC (Dependency Injection) its benefits and types ?


The basic concept of the Inversion of Control pattern (also known as DI - Dependency injection) is that you do not create your objects but describe how they should be created.
You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

i.e., Applying IoC, objects are given their dependencies at creationtime by some external entity that coordinates each object in thesystem. That is, dependencies are injected into objects.
So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.


IoC
  • IoC is one of the techniques used to wire services or components to an application program.
  • You do not create your objects but describe how they should be created.
  • It is a technique that allows object configuration to be moved out of code and into a configuration file (typically XML).
  • In IoC, instead of an application calling the framework, it is the framework that calls the components specified by the application.

Benefits of IoC (DI)
  • Minimizes the amount of code in your application.
    With IOC containers you do not care about how services are created and how you get references to the ones you need.
    You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
  • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases.
    IOC containers make unit testing very easy by manually allowing you to inject your objects into the object under test.
  • Loose coupling is promoted with minimal effort and least intrusive mechanism.
    The factory designpattern is more intrusive because components or services need to be requested explicitly, whereas in IOC the dependency is injected into requesting piece of code.
  • IOC containers support eager instantiation and lazy loading of services.
    Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.


Types of DI (Dependency Injection)

There are 3 types of dependency injection :
1. Constructor Injection (e.g. Spring, Pico container etc)
Dependencies are provided as constructor parameters.

2. Setter Injection (e.g. Spring)
Dependencies are assigned through JavaBeans properties (ex: setter methods).

3. Interface Injection (e.g. Avalon)
Injection is done through an interface.

Note: Spring supports only Constructor and Setter Injection and does'nt supports Interface injection.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.