Back to list
Views:   0
Replies:  0
Archived
,
Reply 1
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...

http://weblogs.asp.net/cazzu/archive/2009/02/02/funq.aspx

It's worth a watch.

Hope this helps...
Rajesh Pillai, Mar 01, 2011
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas