Dependency Injection Container for each Class Library

后端 未结 1 1993
眼角桃花
眼角桃花 2021-01-25 08:22

So, this is the first time I\'m dealing with DI, please correct me if I misunderstood the whole DI thingy.

These are few of my projects:

  1. Web Application/
相关标签:
1条回答
  • 2021-01-25 08:39

    My intention was to have each project having its own DI container (says Unity DI). I'm not sure that each project can have its own DI container.

    As explained here, you should compose all object graphs:

    As close as possible to the application's entry point.

    This place is called the Composition Root:

    A Composition Root is a (preferably) unique location in an application where modules are composed together.

    In other words, the only place that you should use your DI container and configure your application's dependencies is in the start-up project. All other projects should be oblivious to the container and should purely apply Constructor Injection.

    I have read some of the article, showing that it cannot be done

    It can be done, but you shouldn't.

    If each project can have its own DI, when registering the IMapper as instance will it override IMapper of other layers?

    This problem goes away if you apply the Composition Root pattern. In the Composition Root you have full control over which component gets which dependency.

    PRO TIP: Read this book.

    0 讨论(0)
提交回复
热议问题