1

I'm doing poor man's DI (manual injection) in my application. My (pseudo-) composition root looks something like this:

var connectionSettings = new Settings(SqlParameters)
var dataLoader = new SqlDataLoader(connectionSettings)

var data = dataLoader.LoadData() //yuck

var someOtherDependency = new SomeClass(...)
... //a lot of other objects construction

var dataProcessor = new DataProcessor(data, someOtherDependency, ...)

dataProcessor.Process()

I'm not quite happy about the code above. It was intended to only contain object graph construction (new(...)) except for final Process() method call, however unfortunately some other logic (esp. time consuming data loading and conditionals) sneaked in. What is the correct design pattern in such cases? I thought about changing code in DataProcessor from:

public class DataProcessor
{
    public DataProcessor(Data data, otherDependency, ...)
    {
        this.data = data;
        this.otherDependecy = otherDependency;
        ...
    }

    public void Process()
    {
        ... //logic based on data
    }
}

to

public class DataProcessor
{
    public DataProcessor(IDataLoader dataLoader, otherDependency, ...)
    {
        this.DataLoader = dataLoader
        this.otherDependecy = otherDependency;
        ...
    }

    public void Process()
    {
        data = DataLoader.LoadData();
        ... //logic based on data
    }
}

however this is not my preferred solution, as it changes perfectly good class, and implies that data must always be loaded which is not always the case. In unit tests for example I do not load data but just create a mock object.

  • clean composition root from anything other than object construction? - Why do you think it is a good practice? What value does it add to warrant all those code changes? – Achilles Feb 3 '17 at 5:40
  • Well, the rationale behind it is that constructing objects is something fundamentally different than the actual logic of the application. It's almost like boilerplate code. That's why dependency injection frameworks partially automating it became so popular. So it seems like a good idea to separate these two areas. – jqer Feb 4 '17 at 8:39
  • I see what you mean. DI is used not to segregate the object creation code but rather to reduce the coupling between objects and their dependencies. I'm not truly convinced that your first version is wrong (ignoring the DI part) other than looking slightly messy and would love to see any comments from others about this but in any case you'd probably be able to achieve what you want if you add a DI framework that puts the DI process in a configuration file outside of your actual code. – Achilles Feb 4 '17 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.