首页  >  文章  >  web前端  >  Inversify 和 Inversify-inject-decorators

Inversify 和 Inversify-inject-decorators

PHPz
PHPz原创
2024-07-30 20:34:23852浏览

Inversify & Inversify-inject-decorators

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

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

第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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn