這是一個很好的例子,可以讓您輕鬆理解如何反轉和反轉注入裝飾詞。
我將按照以下每個步驟改進程式碼:
第1步:普通課
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); } }
第 2 步:應用依賴注入
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());
第 3 步:應用依賴圖綁定
//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>();`
以上是Inversify 和 Inversify-inject-decorators的詳細內容。更多資訊請關注PHP中文網其他相關文章!