Home  /  Questions  /  Question

88   96.5
Feb 27, 2011

Difference between Factory Pattern and Dependency Injection

What is the difference between Factory Pattern and Dependency Injection?  And when does one use the Factory Pattern over Dependency Injection?

If I write custom xml in my config file and then in my custom factory.cs file I create an interface object with reflection or getsection() from xml. Next, I return an interface to the client like Service Locator Pattern does this then become the Dependency Injection?

I am very confused and need some examples and/or a roadmap.


1,364   100.0
Mar 01, 2011
Factory and DI are different and may be complimentary.  Factory is used to create objects and DI is used to move the responsibility of creating an object outside the main code.

This may seem confusing.  Here's an example.

Say you have a "Home" Controller with an action named "Index".

public class HomeController : Controller
      public ActionResult Index()
              IDashBoardService service = MyFactory.GetDashBoardService<IDashBoardService>();
              var widgets = service.GetAll();     

The above "Index" method creates an instance of IDashBoardService using the MyFactory.  It's kind of generic implementation for representation.

Now, if you observe the "Index" method is responsible for creating an instance of "IDashBoardService".  As application grew in size there may be more services added and the creation of these services will be mixed with the core code.

DI provides a way to abstract away this creation.  There are many ways to do this, the primary being injecting dependencies via constructor or via property.  Shown below is the same above example by using DI (constructor injection).

public class HomeController : Controller
      public ActionResult Index(IDashBoardService service)
              var widgets = service.GetAll();     

In the above code the instance of "IDashBoardService" is being passed by some DI containers while creating the "HomeController".  This can be done by subclassing the DefaultController factory and injecting the required dependencies as required.  In this case the code is pretty clean and only deals with the core logic rather than supporting activities like creating instances and all...

Some of the well known framework available for DI are

1.  Unity Application Block (Microsoft)
2.  Ninject
3.  StructureMap
4.  Castle Windsor
5.  Munq/Funq
6.  Autofac

Do google for more information about these frameworks.... They are pretty useful in many scenarios....

Here's is a set of videos which shows how to develop a DI container using TDD approach...


It's worth a watch.

Hope this helps...
 1 comment
thanks for your answer.I am searching --- Volkan Genç  Mar 08, 2011