DEV Community

Tu Bui
Tu Bui

Posted on

Inversify

This is good example for you to easy understand how inversify work.

I will improve code follow each step below:

Step 1: Normal Class

public class Cart
{
    private readonly IDatabase _db;
    private readonly ILogger _log;
    private readonly IEmailSender _es;

    public Cart()
    {
        _db = new Database();
        _log = new Logger();
        _es = new EmailSender();
    }

    public void Checkout(int orderId, int userId)
    {
        _db.Save(orderId);
        _log.LogInfo("Order has been checkout");
        _es.SendEmail(userId);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2:Apply Dependency Injection

public Cart(IDatabase db, ILogger log, IEmailSender es)
{
        _db = db;
        _log = log;
        _es = es;
 }

 //Dependency Injection simple way
 Cart myCart = new Cart(new Database(),
                   new Logger(), new EmailSender());
 //When you want to change new class. Update here
 myCart = new Cart(new XMLDatabase(),
              new FakeLogger(), new FakeEmailSender());
Enter fullscreen mode Exit fullscreen mode

Step 3: Apply dependency-graph-binding

//Create each Interface
DIContainer.SetModule<IDatabase, Database>();
DIContainer.SetModule<ILogger, Logger>();
DIContainer.SetModule<IEmailSender, EmailSender>();

DIContainer.SetModule<Cart, Cart>();

//MyCart just need to use it
var myCart = DIContainer.GetModule(); 
public Cart()
    {
        _db = DIContainer.GetModule();
        _log = DIContainer.GetModule();
        _es = DIContainer.GetModule();
    }

//When you want to change some module in Cart. Just need to change in where it define.
DIContainer.SetModule<IDatabase, XMLDatabase>();`
Enter fullscreen mode Exit fullscreen mode

Top comments (0)