Dependency Injection: SimpleInjector

Dependency Injection is a pattern that has already proven to make ease of our development. I remember a quote that you sure already heard: “Program to an interface, not an implementation“. Why is it important to rely on the interface instead of the implementation class? The answer is we can refactor it anytime without breaking all the class.

SimpleInjector is one of the DI Library that very easy to use. For example, you have a code for logging. The first version you want to be print in Console.WriteLine only. But afterward, you want to be store in another medium such as a text file, or even put it in the Db.

Here’s some example of the code:

public interface ILogger
{
	void Write(string text);
}

public class Logger : ILogger
{
	public void Write(string text)
	{
		Console.WriteLine(text);
	}
}

Before you call your code, we need to register all the class that we want to use it. This is an example of how to register it and calling the function:

// Create instance of the SimpleInjector
var container = new Container();
// Register Interface ILogger and the implementation of Logger
container.Register();

var logger = container.GetInstance();
logger.Write("Hello world!");

Then let’s make the Logger class a little bit complicated. I add another class:

public interface IMessage
{
	string GetMessage();
}

public class Message : IMessage
{
	public string GetMessage()
	{
		return "Default Logger:";
	}
}

In the Logger class, I modify it to get the default message for logging:

public class Logger : ILogger
{
	private readonly IMessage _message;
	public Logger(IMessage message)
	{
		_message = message;
	}
	public void Write(string text)
	{
		Console.WriteLine(_message.GetMessage() + text);
	}
}

The last piece is we need to register Message class before we call:

// Create instance of the SimpleInjector
var container = new Container();
// Register Interface ILogger and the implementation of Logger
container.Register();
container.Register();

var logger = container.GetInstance();
logger.Write("Hello world!");

The result of the code:

simpleinjector

When you using SimpleInjector, we don’t need to instance manually our class. SimpleInjector will help to do that. Even we can also define the LifeStyle of the object (Scope, Transient, or event Singleton) which will help you a lot.

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.