5
votes

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

1 Answers

6
votes

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.