简体   繁体   English

在控制反转中,回调和依赖注入之间有什么区别?

[英]In Inversion of Control, what is the difference between a callback and dependency injection?

I understand what's going on enough to know I'm missing something. 我了解发生了什么,足以知道我缺少什么。 I get how in DI I'm using and Interface or Abstract Class to define what my function/method can receive. 我知道如何在DI中使用接口或抽象类定义我的函数/方法可以接收的内容。 As long as my object implements or extends the given type, I can pass it to, good decoupling. 只要我的对象实现或扩展给定的类型,就可以将其传递给良好的去耦。

In a callback, I'm passing a function to a method that calls my other function. 在回调中,我正在将一个函数传递给调用另一个函数的方法。 LIke in C, I can use function pointers. 像C一样,我可以使用函数指针。 OOP language same thing but with Interfaces/Abstract Classes. OOP语言是一样的东西,但是带有接口/抽象类。

I see the decoupling, why that's good, the software can be extended, and so on, but not the difference between the two. 我看到了分离,为什么这样好,可以扩展软件,等等,但两者之间没有区别。

What am I missing? 我想念什么?

EDIT: Is DI the pattern and a Callback the implementation? 编辑:DI模式和回调实现吗?

Dependency injection is a software design pattern which as you say lets you decouple your code. 依赖注入是一种软件设计模式,正如您所说的,它可以使代码解耦。 Making for example the ability to swap your SQL backend with an Oracle backend or swapping email hosts in dev environment or live. 例如,使您能够与Oracle后端交换SQL后端或在开发环境或实时环境中交换电子邮件主机。

This naturally descourages adding say database code to your front end project which is obviously not a great idea. 这自然会阻止在您的前端项目中添加说数据库代码,这显然不是一个好主意。

A callback or delegate is where you pass in some code as a parameter to a method. 回调或委托是您在其中将一些代码作为参数传递给方法的位置。 You see this a lot in things like collections where you may want to use different sort functionality in different consumer code. 您会在诸如集合之类的东西中看到很多,您可能希望在不同的使用者代码中使用不同的排序功能。

So if you where to write your own DI container, you would be binding a reference to an interface, say IRepository to a concrete implemention, say SQLRepository or WebRepository. 因此,如果您在哪里编写自己的DI容器,则将绑定对接口的引用,例如将IRepository绑定到具体的实现,例如SQLRepository或WebRepository。 Your DI code what allow consumers to define which concrete implementation to use at compile time either using a configuration file (eg unity) or in code (Ninject). 您的DI代码使消费者可以使用配置文件(例如unity)或代码(Ninject)来定义在编译时使用哪种具体实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM