Can I inject the same dependency into multiple objects of the same type?

83 Views Asked by At

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?

1

There are 1 best solutions below

0
David Osborne On

I would argue that the ListOfFoo class also needs to have its dependencies injected, rather than using the new keyword:

class ListOfFoo
{
   public List<A> fooList;
   private readonly IFooRepository fooRepository;
   public int id;
   
   public ListOfFoo(IFooRepository fooRepository)
   {
      this.fooRepository = fooRepository
   }
   public void LoadList()
   {
      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))
      }

   }
}

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.