Ini adalah contoh yang baik untuk anda mudah memahami cara menyongsangkan & menyongsangkan-menyuntik-perkataan hiasan.
Saya akan menambah baik kod mengikut setiap langkah di bawah:
Langkah 1: Kelas Biasa
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); } }
Langkah 2: Guna Suntikan Ketergantungan
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());
Langkah 3: Gunakan pengikatan graf kebergantungan
//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>();`
Atas ialah kandungan terperinci Inversify & Inversify-inject-decorators. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!