lundi 13 août 2018

Injecting a dependency having constructor parameters in common with the higher level class

Sometimes when I design my classes, I need some dependency classes with similar constructor parameters. Assume we have

interface IDependency {
    void DoSomething();
}

class DependencyClass : IDependency {
    public DependencyClass(int length) {...}
    ...
}

class MainClass {
    public MainClass(int length, IDependency dependency) {...}
    ...
}

MainClass needs an instance of DependencyClass with the same length. I have two methods in mind to deal with it:

  1. Not creating instances of MainClass directly and always getting them from a factory. This way I can make sure that the desired IDependency instance will be provided to MainClass constructor.

  2. Passing a factory interface, say IDependencyFactory, to MainClass constructor instead of IDependency. So that I can get the desired instance of DependencyClass within my MainClass implementation.

I'm not sure if either of them is a good choice. Is there a best practice in this case?

Aucun commentaire:

Enregistrer un commentaire