Pattern: IOC

Description

Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework. It’s a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework.

Examples in .NET :

IOC

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
namespace IOC;
public class NotificationService
{
    private readonly IMessageService _messageService;
 
    public NotificationService(IMessageService messageService)
    {
        _messageService = messageService;
    }
 
    public void SendNotification(string message)
    {
        _messageService.SendMessage(message);
    }
}
public interface IMessageService
{
    void SendMessage(string message);
}

DI

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
namespace IOC;
public class SMSService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine("Sending SMS: " + message);
    }
}
 
public class EmailService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine("Sending email: " + message);
    }
}

Learn More

Source Code for Microsoft implementation of IOC

SourceCode ServiceCollection

Learn More

dofactory
DPH

}

Homework

Implement a simple IoC container that will allow you to register and resolve dependencies. The container should be able to resolve dependencies by type and by name.