11

The two common mechanisms for creating dependency injection bindings, such as through an IOC container, is from an XML configuration or a block of imperative code. In these cases, the key value pair is explicit (i.e. key = requested type, value = returned type).

Still, there is a third "heuristic" approach where an application/IOC container is given only [IMyClass] keys and the container then reflects over a set of application assembly dependencies to find all name-matched concrete classes [MyClass]. Said differently, the "return type" values are discovered rather than declared.

What I'd like to know is twofold:

  1. Which IOC containers (or other late-binding tools) permit the heuristic approach? Does this approach have a more common name?
  2. Are there other binding techniques, besides the three I've listed, which are used in practice?
4

4 回答 4

4

你所说的“启发式”方法就是我所说的约定。大多数 IoC 容器允许您覆盖它们解析绑定的方式,这意味着您可以引入任何您想要的约定。我知道没有这样的默认约定。相反,大多数容器默认什么都不做。您的工作是告诉他们如何通过配置文件或代码解析类型。

我发现一个自定义约定的示例很常见,它可以为您节省大量声明:如果请求的类型是一个以“I”开头并以“Service”结尾的接口类型,则尝试创建和解析具有相同名称的类型除了“我”。IFooService这将自动解析名称FooService。此外,您可以很容易地引入逻辑来决定不同上下文中的不同服务,并且可以在一个共同的地方处理服务实例的生命周期。

由于您可以覆盖大多数 IoC 容器的绑定方式,因此您也可以引入其他行为。然而,一般来说,实际上有两种选择:

  1. 在运行时配置(通过 XML 文件等配置文件)
  2. 在编译时配置(通过声明性的 DSL 类 API 或通过自定义约定或其他形式的自定义逻辑)
于 2011-10-26T07:59:23.147 回答
4

这称为基于约定的配置自动注册,并受以下 .NET DI 容器支持:

用于 DI 容器的最常见配置机制是

  • XML
  • 代码作为配置
  • 基于约定的配置

第四种但不常见的方法是使用属性。托管可扩展性框架是这种方法最突出的例子,这在 Java 中更为常见。

于 2011-10-26T08:12:29.490 回答
1

我通常做了你所说的配置中的自定义步骤。AFAIK 没有容器提供开箱即用的这种策略(在我看来,这不是容器部分,而是应该在容器责任之外的配置内容)。

于 2011-10-26T07:55:55.227 回答
0

由于我使用过StructureMap相当多,我知道如何使用该容器做这样的事情:它基本上是一个自定义注册约定(从初始化或注册表,进入 Scan-lambda 块并找到“约定“ 方法)。

它允许您查看反射类型,然后将它们插入到您认为合适的容器配置中。它应该允许您尝试做的事情。

于 2011-10-26T08:01:00.837 回答