Dynamic selection of interface implementation using IoC

前端 未结 1 410
别跟我提以往
别跟我提以往 2021-01-06 01:16

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

相关标签:
1条回答
  • 2021-01-06 01:55

    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.

    0 讨论(0)
提交回复
热议问题