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.
3