Dependency Injection and Entities

61 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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.