开发者

IoC Dependency Injection for stateful objects (not global)

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开发者_如何学C 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

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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜