IoC dependency injection for stateful objects (non-global)

I am new to this IoC and DI business. I feel like I understand the concept if you are passing through objects that have a global scope, but I don’t understand how this works when you need to go through an object that has a specific logical state. So, for example, if I wanted to insert a human object into a command object of a recording file, how would I dynamically select the correct human object? From what I saw, I could build an object by default, but my disconnect is that you will not use the default object for a person, it must be dynamic. I suppose that an IoC container might just maintain the state of an object for you as it goes through, but then that means that you are dealing with only one person, because there would be no thread safety, would it? I know that I have something missing (maybe something like a factory class), but I need a little more information on how this will work.

+6
dependency-injection ioc-container
source share
2 answers

Well, you can always insert Factory Abstract into your consumer and use it to create locally localized objects.

This is sometimes necessary. See the following examples:

  • MVC, DI (dependency injection) and instantiation of the model from the controller .
  • Is there a template for initializing objects created using the DI container
  • Unable to combine Factory / DI

However, as a rule, we do not use DI for entities, but mainly for services. Instead, entities are usually created through some kind of repository.

+6
source share

When you create a service object (for example, WriteFileService ), you inject things into it that you need internally to complete the operation. Perhaps he needs a file system object or something like that.

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

+4
source share

All Articles