Real-world sample code for Factory Method Design Pattern with Dependency Injection using Autofac in ASP.NET MVC

Gang of Four (GOF) Design Patterns (23 Design Patterns in total) is categorized in three groups:  Creational, Structural, and Behavioral. Factory Method Design Pattern lies under Creational Patterns. Factory Method Design Pattern encapsulate the implementation details of creating objects, which inherits a common base class or which implements a common interface. Factory Method Design Pattern is one of the highly used design pattern.

Autofac is an Inversion of Control (IOC) container for .NET which is used in the below sample code.

Below sample code show how to implement Factory Method Design Pattern with Dependency Injection (DI) using Autofac.

 

Step 1:  Setup Autofac (Inversion of Control container)

Install Autofac.Mvc5 Nuget package. Add Bootstrapper.cs class in App_Start directory:

Update Global.asax class to call Run method of Bootstrapper class as shown below:

Step 2: Add classes participating in Factory Method Design Pattern:

Add the XmlType enum, IProcessXml interface, ProcessType1Xml  class, ProcessType2Xml  class & ProcessType3Xml  class as shown below.

Note here ProcessType1Xml , ProcessType2Xml & ProcessType3Xml  classes implement the common  IProcessXml interface.

Step 3: Set Factory Method using Dependency Injection

Update the SetAutofacContainer() method of Bootstrapper class to set Factory Method using Dependency Injection as shown below:

Step 4: Add ProcessData ActionMethod in HomeController  class that processes xml string based of the XmlType enum.

Add HomeController  controller in which, we have injected Func<XmlType, IProcessXml> processXmlFunction (process xml function delegate) using constructor injection. Also, add ProcessData ActionMethod that processes xml string based of the XmlType.

Func<XmlType, IProcessXml> processXmlFunction: encapsulates a method that has one parameter of XmlType type  and returns a value of the type IProcessXml.

 

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone's Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *