【问题标题】:Dynamic selection of interface implementation using IoC使用 IoC 动态选择接口实现
【发布时间】:2016-04-11 12:34:16
【问题描述】:

我有一种情况,接口的实现是在运行时确定的。例如,我检查一个字符串,然后确定要使用哪个子类,如果没有 IoC,它看起来如下所示:

if (fruitStr == "Apple")
{
    new AppleImpl().SomeMethod();
}
else
{
    new BananaImpl().SomeMethod();
}

AppleImplBananaImpl 两个类都是同一个接口的实现,比如 IFruit

如何使用 IoC/依赖注入来做到这一点,尤其是在 Castle Windsor

【问题讨论】:

标签: c# dependency-injection inversion-of-control castle-windsor ioc-container


【解决方案1】:

这是关于依赖注入的最常见问题,并且在 StackOverflow 上被反复询问。

简而言之,最好使用模式来解决运行时创建问题,而不是尝试将容器用于超过composing object graphs, which is all it is designed for

有几种模式可以用于此,但最好的选择是使用Abstract FactoryStrategycombination of the two。确切的解决方案取决于实例的使用方式——如果您需要几个短期实例并希望在使用后丢弃它们,请使用工厂,或者如果您需要反复使用实例,请使用策略循环而不必每次都重新创建它们。这种组合是高性能和低内存消耗之间的权衡。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2010-12-18
    • 2016-02-09
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多