Dependency Injection: SimpleInjector
Dependency Injection is a pattern that has already been proven to 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.
SimpleInjectoris one of the DI libraries that is very easy to use. For example, you have a code for logging. The first version you want to be printed in Console.WriteLine only. But afterward, you want to store it 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 classes that we want to use. This is an example of how to register it and call 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 Messageclass 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:

When you use SimpleInjector, we don't need to use 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 comment
Your comment is sent privately to the author and isn't published on the site.