如何使用依赖注入容器进行延迟加载?
我对依赖注入容器等很陌生。
我拥有的是一个我想用容器构建的 User 对象。就我而言,用户可能有大量与他/她相关的 Comment 对象,但我不会在每个请求中都需要它们。
以前,我会让用户模型本身创建并加载评论模型,但我意识到这是一个不好的做法。
如果我不想在构建用户时加载所有评论(例如,如果我想延迟加载评论),我如何使用 DI 和 DIC 来实现这一点?
笔记: 我知道已经构建了解决方案,但在了解它们的工作原理之前我不想使用它们。这是一个理论问题,需要学习基础知识,然后我很可能会转向一个既定的框架。
I am new to Dependency Injection Containers and the like.
What I have is a User object that I would like to build with a container. The user, in my case, might have tons of Comment objects associated with him/her, but I won't need them on every request.
Before, I would have had the User model create and load the Comment models itself, but I realize that is a bad practice.
If I don't want to load all the Comment upon building the User (eg - if I'd like to lazily load the comments), how do I achieve this with DI and DIC?
NOTE:
I know there are solutions built, but I don't want to use them until I understand how they work. This is a theoretical question to learn the basics, and then I will most likely switch to an established framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为在模型中加载依赖项是依赖项注入容器的责任。这是 ORM、数据访问对象或应用程序服务的工作。然后,DI 容器负责配置和实例化 ORM、DAO 或服务类。
I don't think that loading dependencies in your Models is the responsibility of the Dependency Injection container. This is the job of an ORM, Data Access Objects or your application services. The DI container then is responsible for configuring and instantiating the ORM, DAO or services classes.