Skip to main content

Pattern: IOC

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.

Purpose of .NET implementation

You want people to work with the file system . Possibly without a file or a directory that exists, but just with implementation.
You want to be able to test the code without the file system.
So you want to abstract the file system.
See file system abstraction in the links below.

Examples in .NET :

IOC

IOC example for Pattern IOC
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

DI example for Pattern IOC

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);
}
}

Download source

See Source Code for Microsoft implementation of IOC

SourceCode ServiceCollection

Learn More

dofactory
DPH
File Providers in ASP.NET Core

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.