各种 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) {...}
}
我们要实现的是:
将ILog
注入Crypter
或注入其中的任何其他classSimpleLogger
。在示例中,SimpleLogger
将被注入到 DefaultRepository
中,而 DefaultRepository
又被注入到 Crypter
中
将 ILog
绑定到 DefaultLogger
用于所有其他绑定。在我们的示例中,DefaultLogger
将被注入到 DefaultRepository
中,而 DefaultRepository
又被注入到 OtherService
中
这是因为 Crypter
class(以及它使用的任何服务)必须记录到一个特殊的地方。但我可以想象这可能适用的类似场景(例如解决循环依赖)。
问题
为什么这在其他 DI 框架中是不可能的?如果是(带有绑定或其他方式),请提供示例。
这不是常见的注入场景吗?
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 违规问题。
情况
我们最近开始寻找 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) {...}
}
我们要实现的是:
将
ILog
注入Crypter
或注入其中的任何其他classSimpleLogger
。在示例中,SimpleLogger
将被注入到DefaultRepository
中,而DefaultRepository
又被注入到Crypter
中
将
ILog
绑定到DefaultLogger
用于所有其他绑定。在我们的示例中,DefaultLogger
将被注入到DefaultRepository
中,而DefaultRepository
又被注入到OtherService
中
这是因为 Crypter
class(以及它使用的任何服务)必须记录到一个特殊的地方。但我可以想象这可能适用的类似场景(例如解决循环依赖)。
问题
为什么这在其他 DI 框架中是不可能的?如果是(带有绑定或其他方式),请提供示例。
这不是常见的注入场景吗?
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 违规问题。