Dynamic selection of interface implementation using IoC

时间秒杀一切 提交于 2019-12-19 03:13:24

问题


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();
}

Both classes AppleImpl and BananaImpl are implementation of the same interface, say IFruit.

How can this be done using IoC/Dependency Injection, especially in Castle Windsor?


回答1:


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.



来源:https://stackoverflow.com/questions/34649735/dynamic-selection-of-interface-implementation-using-ioc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!