12

在我的 StructureMap 引导代码中,我使用自定义约定来扫描程序集并将接口/实现对作为命名实例添加到对象图中。本质上,我有一些逻辑可以检查配置设置并根据各种条件深入到该语句:

registry.For(interfaceType).Use(type)
    .Named(implementationName);

这很好地添加了所有命名实例。但是,如果未指定实例名称,我还想添加一个默认实例。但是,默认实例并不总是添加到图表中的最后一个。有时在扫描期间会添加其他命名实例。不过,无论是否命名,最后添加的实例似乎始终是默认值。

我尝试了各种 fluent API 组合,包括:

registry.For(interfaceType).Add(type);

或者:

registry.For(interfaceType).Use(type);

甚至有些标记为已弃用。但结果行为始终是最后一个是默认行为。因此,如果添加实现的顺序是这样的:

  1. 对于 Logger 接口,使用名为“Log4Net”的 Log4Net 实现
  2. 对于 Logger 接口,默认使用 Log4Net 实现
  3. 对于 Logger 接口,使用名为“Mock”的 Mock 实现

产生的行为是当没有指定名称时,“Mock”实现被用作默认值。在容器中调试AllInstances,我按以下顺序查看:

  1. 名为“Log4Net”的 Log4Net 记录器实例
  2. 一个带有 GUID 名称的 Log4Net 记录器实例(据我所知,与任何其他默认实例一样)
  3. 一个名为“Mock”的模拟记录器实例

但是,在没有实例名称的情况下从容器调用时调试到日志记录语句会导致使用 M​​ock 实现。

有没有办法将默认实例添加到对象图中,同时仍然能够在之后添加命名实例?

4

1 回答 1

26

The Add method will add instances (if you need to add named instances or add multiple instances for to use with collections/enumerations). If no explicit default is registered (using the Use method), the last instance added will become the default instance. The Use method is intended for setting the default instance. If you invoke Use multiple times, the last instance registered will become default.

In order to set a default instance and then register further named instances you should be able to do it like this:

registry.For(typeof(Logger)).Use(typeof(Log4Net)).Named("Log4Net");
registry.For(typeof(Logger)).Add(typeof(Mock)).Named("Mock");

This will make the Log4Net instance the default and also accessible as a named instance. The Mock instance will be available as a named instance.

于 2013-05-28T14:41:48.050 回答