使用IoC动态选择接口实现 [英] Dynamic selection of interface implementation using IoC
问题描述
我有一种在运行时确定接口实现的情况。例如,我检查一个字符串,然后确定要使用哪个子类,没有IoC它看起来像下面这样:
I have a situation where the implementation of an interface is determined at runtime. For example, I check a string and then determine which subclass to use, without IoC it looks like the following:
if (fruitStr == "Apple")
{
new AppleImpl().SomeMethod();
}
else
{
new BananaImpl().SomeMethod();
}
两个类 AppleImpl
和 BananaImpl
是实现相同的界面,例如 IFruit
。
Both classes AppleImpl
and BananaImpl
are implementation of the same interface, say IFruit
.
如何使用IoC /依赖注入来完成,特别是在 Castle Windsor 中?
How can this be done using IoC/dependency injection, especially in Castle Windsor?
推荐答案
这是关于依赖注入的唯一最关心的问题,并在StackOverflow上一再被问到。
This is the single most-asked question about Dependency Injection, and gets asked over and over again on StackOverflow.
简而言之,最好使用模式来解决运行时而不是试图将容器用于构成对象图的 >,这是它的所有设计。
In short, it is best to use patterns to solve runtime creation rather than trying to use the container for more than composing object graphs, which is all it is designed for.
有几种模式可以用于此,但最好的选择是使用抽象工厂,策略,或组合两者。确切的解决方案取决于实例的使用方法 - 如果您需要几个短暂的实例,并且在使用后要丢弃它们,请使用工厂,或者如果您需要在一个或多个循环,而不必每次重新创建它们。该组合是高性能和低内存消耗之间的折衷。
There are several patterns that can be used for this, but among the best options are to use Abstract Factory, Strategy, or a combination of the two. The exact solution depends on how the instance will be used - use a factory if you will be needing several short-lived instances and want to discard them after use, or use a strategy if you need to use the instances over and over again in a loop without having to recreate them each time. The combination is a tradeoff between high performance and low memory consumption.
这篇关于使用IoC动态选择接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!