IoC in C#

Inversion of Control(IoC) is a design mechanism to decouple components dependencies, a light-weight implementation is: TinyIoC, which is also part of Nancy.

IoC idea uses commonly in webUI(and backend server) apps, which is an user friendly solution to cloud deployment management as well as apps in mobile, which should be the right direction in future ADS software tool development.

the idea of IoC can be explained by the following example from register and resolve in unity container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public interface ICar
{
int Run();
}
public class BMW : ICar
{
private int _miles = 0;
public int Run()
{
return ++_miles;
}
}
public class Ford : ICar
{
private int _miles = 0;
public int Run()
{
return ++_miles;
}
}
public class Driver
{
private ICar _car = null;
public Driver(ICar car)
{
_car = car;
}
public void RunCar()
{
Console.WriteLine("Running {0} - {1} mile ", _car.GetType().Name, _car.Run());
}
}

the Driver class depends on ICar interface. so when instantiate the Driver class object, need to pass an instance of ICar, e.g. BMW, Ford as following:

1
2
3
4
5
6
7
8
9
10
11
12
Driver driver = new Driver(new Ford());
driver.RunCar()
```
**to use IoC**, taking UnityContainer framework as example, a few other choices: TinyIoC e.t.c.
```c#
var container = new UnityContainer();
  • Register

create an object of the BMW class and inject it through a constructor whenever you need to inject an ojbect of ICar.

1
2
container.Register<ICar, BMW>();
  • Resolve

Resolve will create an object of the Driver class by automatically creating and njecting a BMW object in it, since previously register BMW type with ICar.


Driver  drv =  container.Resolve<Driver>();
drv.RunCar()

summary

there are two obvious advantages with IoC.

  • the instantiate of dependent class can be done in run time, rather during compile. e.g. ICar class doesn’t instantiate in Driver definition

  • automatic new class management in back.

the power of IoC will be scaled, once the main app is depends on many little services.