带有可变对象的依赖项注入 [英] Dependency Injections with Mutable Objects

查看:72
本文介绍了带有可变对象的依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将将来可能无法使用的任何东西传递给一个类,这会是一个坏主意吗?

Would it be a bad idea to pass anything that could possibly not work in the future to a class?

例如,传递数据库连接(或其他任何传递的信息)可能使它的方法变得无用)到多个类?使用JavaScript时,这些是通过引用传递的,因此,如果在类外部取消了数据库连接,那么类内的对象将无法正常工作?现在这很不好,因为现在看到在方法中使用数据库的所有模型和事物都将不起作用(没有任何通知,现在不能使用所有使用该对象的类)。

For instance, passing a database connection (or anything that can possibly have it's methods rendered useless) to multiple classes? With JavaScript, these are passed by reference, therefore if the database connection is canceled outside of the class, the object within the classes wouldn't work? Now would this be bad, seeing now that all the models and things which use the database in methods will not work (without any notice that all the classes using the object now cannot be used).

推荐答案

数据库连接是传递给类以进行依赖项注入的完美示例。

A database connection is a perfect example of something to pass into a class for dependency injection.

依赖注入对于测试模型/类非常有用,在测试过程中,您想模拟某些服务,例如数据库。在测试中,您可以注入一个模拟数据库功能的模拟对象,而不是注入数据库对象。

Dependency injection is useful for testing your models/classes, and during testing you want to "mock" certain services such as your database. In your tests, instead of "injecting" a database object, you would "inject" a mock object that models your database functionality.

这篇关于带有可变对象的依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆