Revisiting the Factory pattern
A factory creates other objects; it is like a literal real-world factory. We explored in the previous chapter how to leverage the Abstract Factory pattern to create families of objects. A factory can be as simple as an interface with one or more Create[Object]
methods or, even more, a simple delegate. We explore a DI-oriented simple factory in this section. We are building on top of the Strategy pattern example.
In that example, we coded two classes implementing the ILocationService
interface. The composition root used the #define
preprocessor directive to tell the compiler what bindings to compile. In this version, we want to choose the implementation at runtime.
Not compiling the code we don’t need is good for many reasons, including security (lowering the attack surface). In this case, we are simply using an alternative strategy useful for many scenarios.
To achieve our new goal, we can extract the construction logic...