PHP前端开发

Inversify 和 Inversify-inject-decorators

百变鹏仔 3个月前 (10-14) #JavaScript
文章标签 Inversify

这是一个很好的例子,让您轻松理解如何反转和反转注入装饰词。

我将按照以下每个步骤改进代码:

第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 InterfaceDIContainer.SetModule<idatabase database>();DIContainer.SetModule<ilogger logger>();DIContainer.SetModule<iemailsender emailsender>();DIContainer.SetModule<cart cart>();//MyCart just need to use itvar 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>();`</idatabase></cart></iemailsender></ilogger></idatabase>