Dependency Injection Container for each Class Libr

2019-03-01 14:29发布

问题:

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/ Web API Project - Depends on Service Class + inject Automapper (Configuration only applicable for current project)
  2. Service (Class Library) - Depends on Data Class + inject Automapper (Configuration only applicable for current project)
  3. Data (Class Library)

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.

I have read some of the article, showing that it cannot be done (not sure if i interpret them correctly) but I'm not sure why?

If it cannot be done, can anyone explain it and how can I achieve this and I doesn't want to register the classes in Data Layer in the Application Layer DI.

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

回答1:

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.