问题描述
我是这个IoC和DI业务的新手,如果您传递的对象是全球范围的对象,我感觉很明白,但是当您需要传递对象时,我不知道它的工作原理具有特定逻辑状态的对象。因此,例如,如果我想将人员对象注入到写入文件命令对象中,我将如何动态选择正确的人员对象?从我所看到的,我可以默认构造该对象,但是我的断开连接是您不会使用默认的person对象,它需要是动态的。我假设IoC容器可能只是在传递对象时为您维护对象的状态,但是假设您只处理一个人对象,因为没有线程安全,对吗?我知道我缺少一些东西(也许是一个工厂类的东西),但我需要更多有关它如何工作的信息。
I'm new to this IoC and DI business- I feel like I get the concept if you are passing along objects that are of a global scope, but I don't get how it works when you need to pass around an object that is of a specific logical state. So, for instance, if I wanted to inject a person object into a write file command object- how would I be able to choose the correct person object dynamically? From what I have seen, I could default construct the object, but my disconnect is that you wouldn't use a default person object, it would need to be dynamic. I assume that the IoC container may just maintain the state of the object for you as it gets passed around, but then that assuems you are dealing in only one person object because there would be no thread safety, right? I know I am missing something, (maybe something like a factoryclass), but I need a little more information about how that would work.
推荐答案
好吧,您始终可以将注入您的消费者,并使用它来创建
Well, you can always inject an Abstract Factory into your consumer and use it to create the locally scoped objects.
有时这是必要的。请参阅以下示例:
This is sometimes necessary. See these examples:
- MVC, DI (dependency injection) and creating Model instance from Controller
- Is there a pattern for initializing objects created via a DI container
- Can't combine Factory / DI
但是,一般而言,我们通常不对实体使用DI,而对服务而言。实体通常是通过某种存储库创建的。
However, in general we tend to not use DI for Entities, but mostly for Services. Instead, Entities are usually created through some sort of Repository.
这篇关于有状态对象的IoC依赖注入(非全局)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!