如果依赖注入的还未初始化_如何使用初始化程序进行Swift依赖注入

如果依赖注入的还未初始化

Dependency Injection feel like a very complicated topic but in fact it is very simple. We as devs all try to follow design principle like SOLID so that our code is properly structured in a modular way and not a spaghetti code. Dependency injection really help with this. It also helps in mocking/testing our code.

依赖注入感觉像一个非常复杂的主题,但实际上它很简单。 我们所有开发人员都尝试遵循SOLID之类的设计原则,以便我们的代码以模块化的方式(而不是意大利面条式代码)正确地进行结构化。 依赖注入确实对此有所帮助。 它还有助于模拟/测试我们的代码。

Dependency injection literally means injecting the dependency. In programming world it means injecting the dependencies our code needs in order to work. There are three flavors of dependency injection in Swift

依赖项注入从字面上意味着注入依赖项。 在编程世界中,这意味着注入代码才能正常工作。 Swift有三种类型的依赖注入

  1. Initializer Based

    基于初始化
  2. Property Based

    基于属性
  3. Parameter Based

    基于参数

In this blog we will focus on Initializer Based Dependency Injection. Lets take a look at this example

在此博客中,我们将重点介绍基于初始化的依赖注入。 让我们看一下这个例子

If you look at the example above, FileUploader instance initialization is dependent on file manager and network manager. So this is a very tightly coupled code. We can use initializer based Swift Dependency Injection to make this a little better

如果查看上面的示例,则FileUploader实例的初始化取决于文件管理器和网络管理器。 因此,这是一个非常紧密耦合的代码。 我们可以使用基于初始化的Swift Dependency Injection使它更好一点

Image for post

So this subtle change makes a huge difference, instead of hardcoding file manager and network manager in the init method of FileUploader we are passing the required/dependency as parameters externally. This is basically what dependency injection is. We will talk about other flavors of dependency injection in coming articles.

因此,这种微妙的变化带来了很大的不同,我们没有在FileUploader的init方法中对文件管理器和网络管理器进行硬编码,而是在外部传递了required / dependency作为参数。 这基本上就是依赖注入。 在接下来的文章中,我们将讨论依赖注入的其他形式。

Originally published at https://www.shashankthakur.dev.

最初发布在 https://www.shashankthakur.dev

翻译自: https://medium.com/@shashank.thakur/how-to-do-swift-dependency-injection-with-initializers-1205ff830faf

如果依赖注入的还未初始化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值