Inversion of Control & Dependency Injection

What is IOC Principle: Inversion of control (IoC) is a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework.

In simple words, IOC is inverting the control from called class to calling class.

DI: Dependency Injection is a design principle in which code creating a new object supplies the other objects that the new object depends upon for operation. This is a special case of inversion of control. Often a dependency injection framework (or “container”) is used to manage and automate the construction and lifetimes of interdependent objects.

DI is ability to supply(inject) external dependencies into a class at run time.

Ways to Inject Dependency:

  1. Constructor (most popular): In this all dependencies are injected while creating instance of the class.
  2. Method: Here, Dependencies are injected while calling the method.
  3. Dependencies are set by calling a setter method an injecting dependency in setter.

Example: You can view this article’s sample on GitHub.

First code sample is without DI.

public class BurgerOrderWithOutDI

{

private IBurgerVendor _burgerVendor;

public BurgerOrderWithOutDI(string burgerVendorType)

{

if (burgerVendorType == “BurgerKing”)

_burgerVendor = new BergerKing();

else

_burgerVendor = new McDonalds();

}

public void PrepareBurger()

{

_burgerVendor.PreppareBurger();

}

}

following code is with Dependency Injection implemented

class BurgerOrderWithDI

{

private IBurgerVendor _burgerVendor;

public BurgerOrderWithDI(IBurgerVendor burgerVendor)

{

this._burgerVendor = burgerVendor;

}

public void PrepareBurger()

{

_burgerVendor.PreppareBurger();

}

}

List of popular DI Container for .Net

Today, there are a lot of excellent DI Containers that are available for .NET. Here, I am sharing the list of most useful DI Container for .Net framework.

  1. Castle Windsor
  2. Structure Map
  3. Unity
  4. NET
  5. Unity
  6. Ninject
  7. Autofac

Author: Rupesh

Hi! I'm Rupesh, a funophile and technophile. I'm an Application Developer, Solution Architect and IT-Consultant, and an author in the works. I am a Microsoft certified Professional and Solution Developer (MCP and MCSD).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s