Dynamic selection of interface implementation using IoC

人走茶凉 提交于 2019-11-30 22:32:49
NightOwl888

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.

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