Question

Given the class:

public class Foo : IFoo
{
  private IBarRepository repository

  public Foo(IBarRepository repository)
  {
     this.repository = repository
  }

  public IList<IBar> Bars { get; private set; }
}

My long standing instinct is to initialise the list of IBar in the constructor: this.Bars = new List<IBar>(); but using Constructor Injection, the Single Responsibility of the constructor is for it to set the dependancies for the class.

What is the best way to handle this?

Should I have a collection initialiser that I call in any method before using the collection?

private void InitialiseCollection()
{
  if (this.Bars == null)
  {
     this.Bars = new List<IBar>();
  }
}

public void Add(IBar bar)
{
    this.InitialiseCollection();
    this.Bars.Add(bar)
}
Was it helpful?

Solution

Well, the simple answer to your question is

public readonly IList<IBar> Bars = new List<IBar>();

But I think you should question your premise.

but using Constructor Injection, the Single Responsibility of the constructor is for it to set the dependancies for the class.

Where have you read that? It's entirely incorrect.

It doesn't matter if you're using Constructor Injection or not. Your constructor's responsibility is to construct an object, fully initialized, with all the dependencies required to operate on that object. Those dependencies can be other services or state or values that distinguish this object from another object of its type.

OTHER TIPS

The Single Responsibility principle applies to the class as a whole, not just to the constructor. Also, resist the urge to initialize the Bars variable using that last method - if you are using injection, it should be responsible for giving you a complete and working instance of Foo or none at all if it can't resolve the object to pass to the constructor.

Licensed under: CC-BY-SA with attribution
scroll top