1

I have two classes and have one to many relationship as shown below

public class User
{
    public string Name{get;set;}
    public IList<Address> Addresses{get;set}
}

public class Address
{
   public string StreetAddress{get;set;}
   public User User{get;set;}
}

To add address to user I need to initiate Addresses property in User constructor as

public User()
{
   this.Addresses=new List<Address>();

}

Is this scenario good candidate to use DI to initiate List or should I initiate the Address list in constructor as shown.

WorkInProgress
  • 393
  • 6
  • 16
  • 1
    I doubt it, are you just initialising it to an empty list? If so, what is there to inject here? I'm not sure you quite understand what dependency injection is. – DavidG Nov 19 '14 at 16:14

2 Answers2

0

If the the address data itself is required to construct an instance of User, it may be a candidate for DI. But if's just a matter of making sure the list is instantiated, then your code is correct as-is.

Phil Sandler
  • 27,544
  • 21
  • 86
  • 147
0

In this case Dependency Injection would be overkill. Dependency Injection is usually used to initialize complex networks of services. Here you are dealing with a network of data objects that map to the piece of world you are translating into code: a composition between User and Address is therefore sufficient, and you must initialize collections in the constructor.

Luca L.
  • 75
  • 7