This is good example for you to easy understand how inversify & Inversify-inject-decoration word.
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); } }
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());
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>();`
The above is the detailed content of Inversify & Inversify-inject-decorators. For more information, please follow other related articles on the PHP Chinese website!