使用 Prism 时,哪个组件负责配置容器?

When using Prism, which component is responsible for configuring the container?

我见过两种方法: 方法一强制 Shell 在编译时引用所有模块(这似乎与 Prism 库的模块化性质的目的相反)。在此方法中,Bootstrapper 使用编译时已知的类型配置容器。

在第二种方法中,Bootstrapper 配置容器以提供容器实例 class(IUnityContainer 或您拥有的)。这允许 Shell 项目对加载的模块一无所知,但强制所有模块依赖于给定的 DI 框架(因为 prism 似乎没有配置容器的通用机制)。

哪种方法更好,还是我遗漏了一些关键信息?

类型在容器中的注册方式取决于容器类型本身。 Prism 完全支持两个容器:MEF 和 Unity。

您可以在 Development Guide 中阅读有关类型注册的信息:

Registering Types with the Unity Container

During initialization, a type can register other types, such as views and services. To do this, the type will need to have the container injected into the module constructor. The registration can also be performed outside the code through configuration.

Registering Types with MEF

MEF uses an attribute-based system for registering types with the container. As a result, adding type registration to the container is simple: it requires the addition of the [Export] attribute to a type.

因此使用 Unity 您有两个选择:容器引用注入和配置。对于 MEF,可以使用属性和容器注入。

如果您想使用其他容器实现,例如 Autofac,您必须为 Prism 提供一个适配器。

开发基于 Prism 的应用程序,您必须选择一种 DI 容器类型。因此,将所有模块与一个 DI 框架耦合起来并没有错。当然,您可以通过使用例如IServiceLocator 界面。但正如 Development Guide 所述:

IServiceLocator is not meant to be the general-purpose container. Containers have different semantics of usage, which often drives the decision for why that container is chosen.

In the following situations, it may be appropriate for you to use the IServiceLocator:

  • You are an independent software vendor (ISV) designing a third-party service that needs to support multiple containers.
  • You are designing a service to be used in an organization where they use multiple containers.