I am refactoring some code to use DI, and I set it up like this:
class ListOfFoo
{
public List<A> fooList;
private readonly IFooRepository fooRepository;
public int id;
public void LoadList()
{
fooRepository = new FooRespository(DataBase.Main); //static Db class helper
this.fooList = new List<Foo>();
var results = {...some db calls and logic...};
foreach (var res in results)
{
this.fooList.Add(new Foo(this.id, res.StartTime, fooRepository))
}
}
}
class Foo
{
private readonly IFooRepository _repo;
public int id;
public DateTime startTime;
Foo(int _id, DateTime _startTime, IFooRepository _repo)
{
repo = _repo;
id = _id;
startTime = _startTime;
}
private DateTime GetEndTimeFromDataBase()
{
return _repo.LoadEndTime(this.id, this.startTime);
}
Is this going to create problems? Or is this the correct way to set up DI in this instance?
I would argue that the
ListOfFooclass also needs to have its dependencies injected, rather than using thenewkeyword:I would also argue that the
FooRepository's dependency on the database access component is also managed via DI and not as a static reference.