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:
- Constructor (most popular): In this all dependencies are injected while creating instance of the class.
- Method: Here, Dependencies are injected while calling the method.
- 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.
- Castle Windsor
- Structure Map
- Unity
- NET
- Unity
- Ninject
- Autofac