Friday 15 December 2017

Clean Factory Design Pattern with IoC container

Audience


This article expects audience have familiarity with Dependency Inversion Principle (DIP) and Factory Design Pattern. For simplicity, the code is not defensive and there is no guarded statements. The code is using Simple Injector, but the described principles applies to other IoC container frameworks as well. The source code of the examples can be found in github by following this link


Problem


When implementing a factory class in a project which uses a Inversion of Control (IoC) container, and you arrive to the solution described below, then this article is for you:
using System;
using DirtyFactory.Dependencies;

namespace DirtyFactory.Processors
{
 internal class ProcessorFactory : IProcessorFactory
 {
  private readonly IDependencyOne _depOne;
  private readonly IDependencyTwo _depTwo;
  private readonly IDependencyThree _depThree;

  public ProcessorFactory(IDependencyOne depOne, IDependencyTwo depTwo, IDependencyThree depThree)
  {
   _depOne = depOne;
   _depTwo = depTwo;
   _depThree = depThree;
  }

  public IProcessor Create(RequestType requestType)
  {
   switch(requestType)
   {
    case RequestType.Internal:
     return new InternalProcessor(_depOne, _depTwo);
    case RequestType.External:
     return new ExternalProcessor(_depOne, _depThree);
    default:
     throw new NotImplementedException();
   }
  }
 }
}