这是一个很好的例子,让您轻松理解如何反转和反转注入装饰词。
我将按照以下每个步骤改进代码:
第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>();` </idatabase></cart></iemailsender></ilogger></idatabase>
登录后复制
以上就是Inversify 和 Inversify-inject-decorators的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:momo,转转请注明出处:https://www.dingdanghao.com/article/664814.html