Search code examples
c#design-patternsinversion-of-controlfactory

Simple factory and IOC


I have a class A{} class B:A{} class C:A{} and class D{} D has methods that need to to use B and methods that need to use C.

in the future I will probably have more classes that inherit from A that Dwill need to use

Should D have a constructor like:

  1. public D(B b, C c)

  2. or should A get a simple factory (F) that will return the correct class. and then the constructor will be public D(F f)

F will have a CreateInstance method that will get enum and return the correct type.

full injection would keep all in the composition root. simple factory would simplify the constructor.


Solution

  • The issue you need to be mindful of here is introducing opaque dependencies via the factory approach.

    At this point in time, D depends on B and C. Using a constructor like:

    public D(B b, C c)
    {
    }
    

    makes the dependencies transparent. I.e. it's clear what this class needs to do its job and these things can be provided directly. Furthermore, automated testing is a little easier as you can provide fakes directly without having to provide a fake factory that provides the other fakes.

    Using a factory reduces this clarity, but does add convenience, and a degree of future-proofing by reducing the number of dependencies that must be passed in.

    Personally, I would stick with providing the dependencies directly until the constructor signature was unwieldy or a higher level abstraction, like a factory, was clearly needed. The fact that the class depends on both B and C gives off a clear design message that an abstraction like a factory might obscure.