When and Why to Use UNITY Framework in .NET? Inversion of Control (IOC) and Dependency Injection(DI)
UNITY Framework is a framework of Microsoft to achieve Inversion of Control / Dependency Injection Design Pattern. IOC is a principle while DI is a way of implementing IOC. Unity is described as a lightweight, extensible dependency injection container. Lets see when and why to use Unity Framework?
UNITY Framework removes Tight Coupling of Classes and Objects and make them loosely coupled. UNITY Framework facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies. Using dependency injection will make the application more flexible to changes and more maintainable. Instead of compile time dependencies, UNITY Framework offers runtime loading and initialization of components, which makes solutions load on demand.
Example of Dependency and Tight Coupling
Consider the below example. We have a Customer class which contains an Address class object. The biggest issue with the code is tight coupling between classes. In other words the customer class depends on the address object. So for any reason address class changes, it will lead to change and compiling of Customer class also. So, if for any reason the address object is not able to create, the whole customer class will fail in the constructor initialization itself.
public class Customer
private Address address;
address = new Address();
Ways to implement Dependency Injection
In DI, we have four broader ways to implement Dependency Injection:
1. Constructor way
2. Exposing setter and getter
3. Interface implementation
4. Service locator
Why to use Unity?
1. It provides simplified object creation, especially for hierarchical object structures and dependencies, which simplifies application code.
2. It supports abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns.
3. It increases flexibility by deferring component configuration to the container.
4. It has a service location capability; this allows clients to store or cache the container. This is especially useful in ASP.NET Web applications where developers can persist the container in the ASP.NET session or application.
When to Use Unity?
1. You have dependencies between objects.
2. The dependencies are complex and you need a way to abstract them.
3. You want to be able to change your dependencies at runtime.
4. You want to use constructors, properties or method calls injections.