IoC Dependency Injection for stateful objects (not global)

孤人 提交于 2019-12-09 06:07:20

问题


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.


回答1:


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

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.




回答2:


When you construct an service object (e.g. WriteFileService), you inject into it things it needs internally to complete it's job. Perhaps it needs a filesystem object or something.

The Person object in your example should be passed to the service object as a parameter to a method call. e.g. writeFileService.write(person)



来源:https://stackoverflow.com/questions/4676477/ioc-dependency-injection-for-stateful-objects-not-global

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!