Composition Root 和 Composer 之间的关系

Relation between Composition Root and Composer

我阅读了 Dependency Injection Principles, Practices, and Patterns 并且 我试图找出 Composition RootComposer.

之间的区别

在书中他们的定义是:

Composition Root is a single, logical location in an application where modules are composed together.

Composer is a unifying term to refer to any object or method that composes Dependencies. It’s an important part of the Composition Root. The Composer is often a DI Container, but it can also be any method that constructs object graphs manually (using Pure DI).

Composition Root 更像是我们应该在其中创建应用程序图的 place/location 的名称,而 Composer 是实际做的事情?或者是别的东西?

If you use a DI Container, the Composition Root should be the only place where you use the DI Container.

Composition Root 中您还可以拥有什么?不就是一个DI Container吗?

public class CompositionRoot
{        
    public static IContainer Compose()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<Calculator>().As<ICalculator>().SingleInstance();


        return builder.Build();
    }
}

此致

Composition Root 可以被视为架构 Module 甚至 Layer。它可以拥有将应用程序连接在一起所需的所有基础设施,这些基础设施不属于任何较低层(例如表示层、域层或数据访问层)。想想代码:

  • 从消息队列中读取并将消息分派给应用程序,
  • 应用横切关注点的装饰器,
  • 将应用程序与外界连接起来的适配器实现

Composition Root 可以拥有所有这些基础设施代码,而 Composer 将只包含通知所有这些代码片段的代码,确保根据它们的生活方式进行缓存,并从这些创建的组件中构建对象图。