title: Removing conditional "new" keyword dependency from a method
body: <p>I'm currently in the middle of learning DI &amp; IoC principles. So, I stumbled upon such scenario where I have a method with a dependency that can not be injected via constructor. Also, I can not pass it as a method parameter because creation of that instance is conditional + it can only be instanciated with parameters of its own. Here is a super-simplified version of my Employee and WorkYear classes: </p>
  
  <pre><code>public abstract class Employee
  {
      private List&lt;WorkYear&gt; _workYears;
      // other private fields....
  
      protected Employee(IDependency1 dep, etc...)
      {
           WorkYears = new List&lt;WorkYear&gt;();
  
           // other components initialization....
      }
  
      public IEnumerable&lt;WorkYear&gt; WorkYears
      {
          get =&gt; _workYears.AsReadOnly();
          private set =&gt; _workYears = value.ToList();
      }
  
      public void StartWorking(DateTime joinedCompany)
      {
          List&lt;PayPeriod&gt; periods = // Calculating periods...
          WorkYear year = WorkYears.FirstOrDefault(y =&gt; y.CurrentYear == joinedCompany.Year);
  
          if (year == null)
          {
              // Here is the problem:
              year = new WorkYear(joinedCompany.Year, this, periods);
  
              AddYear(year);
          }
          else
          {
              // Logic when year not null
          }
  
          year.RecalculateAllTime();
      }
  
      public void AddYear(WorkYear workYear) =&gt; _workYears.Add(workYear);
  
      // More code...
  }
  
  
  public class WorkYear  
  { 
      public WorkYear(int currentYear, Employee employee, List&lt;PayPeriod&gt; periods)
      {
          Employee = employee;
          EmployeeId = employee.Id;
          CurrentYear = currentYear;
          PayPeriods = periods ?? new List&lt;PayPeriod&gt;();
  
          foreach (PayPeriod period in PayPeriods)
          {
              period.WorkYear = this;
              period.WorkYearId = Id;
          }
      }
  
       // More code...
  }
  </code></pre>
  
  <p>As you can see I only need a new instance of a WorkYear if Employee doesn't already have it. I found a thread that suggested to use simple factory class to solve similar issue. Such solution could work, but how do I handle parameters without which the WorkYear can not be instantiated? </p>
  
  <p>Would be great to see an example of how to approach this problem.</p>