各种 DI 框架中的上下文相关注入

Context dependent injections in various DI frameworks

情况

我们最近开始寻找 NInject 的替代品。我们查看了 Simple-Injector、AutoFac 和 StructureMap。但是在我们的测试中,我们无法重现在 NIinject 中可行的绑定,但在其他框架中则不行。

问题

假设我们有以下接口,这些接口通常通过多个应用程序使用:

public interface IRepository {...}

public interface ILog {...}

使用 IRepository 的默认实现:

public class DefaultRepository : IRepository {
    public DefaultRepository(ILog logger) {...}
}

ILog 的两个实现 - 一个 DefaultLogger 和另一个 SimpleLogger.

和两个消耗 IRepository 的 classes:

public class Crypter {
    public Crypter(IRepository repository) {...}
}

public class OtherService {
    public OtherService(IRepository repository) {...}
}

我们要实现的是:

这是因为 Crypter class(以及它使用的任何服务)必须记录到一个特殊的地方。但我可以想象这可能适用的类似场景(例如解决循环依赖)。

问题

Why is this not possible in the other DI frameworks?

我不能代表其他 DI 容器,但是 Simple Injector 支持基于上下文的注入。看看 Context based injection in the documentation.

除此之外,还有许多关于此的 Whosebug 问题,例如:

Is this not a usual injection scenario?

这取决于。简单注入器文档 states:

In many cases context based injection is not the best solution, and the design should be reevaluated. In some narrow cases however it can make sense.

基于上下文的注入的一个常见误用是解决 Liskov Substitution Principle 违规问题。