IoC Dependency Injection for stateful objects (not global)

前端 未结 2 820
北荒
北荒 2021-02-06 08:05

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 p

相关标签:
2条回答
  • 2021-02-06 08:43

    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.

    0 讨论(0)
  • 2021-02-06 09:00

    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 讨论(0)
提交回复
热议问题