
这是一个很好的例子,让您轻松理解如何反转和反转注入装饰词。
我将按照以下每个步骤改进代码:
第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(); DIContainer.SetModule (); DIContainer.SetModule (); DIContainer.SetModule (); //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 ();`










