Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 factoryclass), but I need a little more information about how that would work.

like image 710
mytwocents Avatar asked Jan 13 '11 03:01

mytwocents


1 Answers

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.

like image 82
Mark Seemann Avatar answered Sep 29 '22 00:09

Mark Seemann