Dependency Injection using Ninject in ASP.NET MVC

What is Dependency Injection?
In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. – Wikipedia. It makes software components are loosely coupled.

Advantages of Dependency Injection
• Flexibility to use alternative implementation of service.
• Configurable & easy to use
• Make system loosely couple
• Code becomes more reusable, testable, readable and manageable.
• Reduction of boilerplate code in the application objects

What is Ninject?
• Open Source Inversion of Control (IOC)
• It is a Dependency Injector for .NET created by Nate Kohari
• It’s very easy to use.
• Easily add from nuget.
• For more information visit Ninject.org
Let’s come to the implementation of DI using Ninject in ASP.NET MVC

Tools and Technology used
I used following tools and technology to develop the project –

1. Visual Studio 2013
2. Visual C#
3. ASP.NET MVC 5
4. Entity Framework 6
5. Razor view engine
6. Ninject for MVC5

Step 1: Create a ASP.net MVC Project
From Visual studio 2013, choose File->Project as below

01

Select MVC Template and click OK

02

Step 2: Create a model name Employee

Create a Model name Employee in model folder

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
        public string Dept { get; set; }
        public string BloodGroup { get; set; }
    }

Step 3: Change or Add Connection String
Change or Add connection string in Web.config


 
     
  

Step 4: Create a Context class


Create HRMContext Class in Repository folder.

    public class HRMContext : DbContext
    {
        public HRMContext()
            : base("DefaultConnection")
        {
        }
        public DbSet < Employee > Employees { get; set; }
    }

Step 5: Create Repository Interface and Concrete Class
Create IEmployeeRepository Interface and EmployeeRepository class in Repository folder

    public interface IEmployeeRepository : IDisposable
    {
        IQueryable  All { get; }
        Employee Find(int? id);
        void InsertOrUpdate(Employee employee);
        void Delete(int id);
        void Save();
    }


    public class EmployeeRepository : IEmployeeRepository
    {

        HRMContext context;
        public EmployeeRepository(HRMContext context)
        {
            this.context = context;
        }

        public IQueryable  All
        {
            get { return context.Employees; }
        }

        public Employee Find(int? id)
        {
            Employee objEmployee = new Employee();
            objEmployee = context.Employees.Where(p => p.Id == id).FirstOrDefault();
            return objEmployee;
        }

        public void InsertOrUpdate(Employee employee)
        {
            if (employee.Id == default(int))
            {
                // New entity
                context.Employees.Add(employee);
            }
            else
            {
                // Existing entity
                context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var employee = context.Employees.Find(id);
            context.Employees.Remove(employee);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }

Step 6: Install Ninject from nuget

03


Step 7: Map Interface and Concrete class in Ninject

Go to NinjectWebCommon file in App_Start folder. Add the following line for IEmployee Interface and Employee concrete class.

public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// 
        /// Starts the application
        /// 
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }
        
        /// 
        /// Stops the application.
        /// 
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
        
        /// 
        /// Creates the kernel that will manage your application.
        /// 
        /// The created kernel.
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind().To();

                kernel.Bind().To();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// 
        /// Load your modules or register your services here!
        /// 
        /// The kernel.
        private static void RegisterServices(IKernel kernel)
        {
        }        
    }

Step 8: Create Controller and Views
Click Right button on Controller Folder->Add Controller. Choose its name as EmployeeController. Now choose scaffolding template for the controller as follows.

04

After clicking Add button, Employee Controller and Corresponding actions and views will be created automatically.

Step 9: Modify the controller

Modify the controller – use repository instead of context directly.

    public class EmployeesController : Controller
    {
        private readonly IEmployeeRepository repository;

        public EmployeesController(IEmployeeRepository objIrepository)
        {
            repository = objIrepository;
        }

        // GET: Employees
        public ActionResult Index()
        {
            return View(repository.All.ToList());
        }

        // GET: Employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = repository.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: Employees/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Designation,Dept,BloodGroup")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                repository.InsertOrUpdate(employee);
                repository.Save();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        // GET: Employees/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = repository.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Designation,Dept,BloodGroup")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                repository.InsertOrUpdate(employee);
                repository.Save();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: Employees/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = repository.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            repository.Delete(id);
            repository.Save();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                repository.Dispose();
            }
            base.Dispose(disposing);
        }
    }

Step 10: Run command in Package Manager Console

To find Package manager console go to

Tool->NuGet Package Manager -> Package Manager Console

Now, build the application and run the following command one by one in Package Manager Console.

PM> Enable-Migrations -ContextTypeName HRMContext
PM> Add-Migration initialmigration
PM> Update-Database -Verbose

Step 11: Add a menu
Add a menu name employee in _Layout.cshtml page to create a menu.

                

Run the application and click “Employee” menu. Now you can create, delete, read update employee information.

05

Generic Repository Pattern with ASP.NET MVC and Entity Framework

Introduction
You may introduce with an Object Oriented Design Principle name DRY – Don’t repeat yourself. It is more important in Multi-tier architecture. We can use generic repository pattern to implement DRY.

What is Repository Pattern?
In most of the business operation we have to perform CRUD (Create, Read, Update and Delete) operation. A repository basically works as a mediator between our business logic layer and our data access layer of the application

Benefits of Repository Pattern

  • Centralizes data logic or service logic.
  • Provides a substitution point for the unit tests for both business logic and data access logic
  • Provides a flexible architecture
  • Can adopt new change easily
  • Domain driven development is easier


What is Generic Repository Pattern?

Generic Repository is a pattern by which we can use single repository for data access of all models. Generally, we used one repository for one model to access data.

Benefits of Generic Repository Pattern

  • Reduce redundancy of code
  • Force developer to work same pattern – Possibility of less error or no error
  • Easy to maintain – Centralize data access logic

Implementation Repository Pattern with ASP.NET MVC and Entity Framework

Let’s consider a project to keep Employee Information. Here I will show CRUD operation on employee information.
Tools and Technology used
I used following tools and technology to develop the project – Implementation of generic repository

  • Visual Studio 2013
  • Visual C#
  • ASP.NET MVC 5
  • Entity Framework 6
  • Razor view engine


Step 1:
Create an ASP.NET MVC 5 application using Visual Studio 2013. I kept the application name “GenericRepo”.
Help: How to create first application using asp.net MVC
Step 2: Configure connection string in web.config

  
    
  

Step 3: Create Model – “Employee”

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string FatherName { get; set; }
        public string MotherName { get; set; }
        public string Designation { get; set; }
        public string Dept { get; set; }
    }

Step 4: Create a DbContext name GenericDbContext in Repository folder.

    public class GenericRepoContext : DbContext
    {
        public GenericRepoContext()
            : base("DefaultConnection")
        {
        }

        public DbSet Employees { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        }
    }

Step 5: Create IGenericRepository and GenericRepository in Repository folder


    interface IGenericRepository where T : class
    {
        IEnumerable SelectAll();
        T SelectByID(object id);
        void Insert(T obj);
        void Update(T obj);
        void Delete(object id);
        void Save();
    }

public class GenericRepository : IGenericRepository where T : class
    {
        private GenericRepoContext db = null;
        private DbSet table = null;
        public GenericRepository()
        {
            this.db = new GenericRepoContext();
            table = db.Set();
        }
        public GenericRepository(GenericRepoContext db)
        {
            this.db = db;
            table = db.Set();
        }
        public IEnumerable SelectAll()
        {
            return table.ToList();
        }
        public T SelectByID(object id)
        {
            return table.Find(id);
        }
        public void Insert(T obj)
        {
            table.Add(obj);
        }
        public void Update(T obj)
        {
            table.Attach(obj);
            db.Entry(obj).State = EntityState.Modified;
        }
        public void Delete(object id)
        {
            T existing = table.Find(id);
            table.Remove(existing);
        }
        public void Save()
        {
            db.SaveChanges();
        }
    }

Step 6:
Create a controller name – EmployeeController. Select template “MVC5 Controller with read/write action”

    public class EmployeeController : Controller
    {
        private IGenericRepository repository = null;
        public EmployeeController()
        {
            this.repository = new GenericRepository();
        }


        // GET: Employee
        public ActionResult Index()
        {
            var employee = repository.SelectAll().ToList();
            return View(employee);
        }

        // GET: Employee/Details/5
        public ActionResult Details(int id)
        {
            var employee = repository.SelectByID(id);
            return View(employee);
        }

        // GET: Employee/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Employee/Create
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                repository.Insert(employee);
                repository.Save();

                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: Employee/Edit/5
        public ActionResult Edit(int id)
        {
            var employee = repository.SelectByID(id);
            return View(employee);
        }

        // POST: Employee/Edit/5
        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            try
            {
                repository.Update(employee);
                repository.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Employee/Delete/5
        public ActionResult Delete(int id)
        {
            var employee = repository.SelectByID(id);
            return View(employee);
        }

        // POST: Employee/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                repository.Delete(id);
                repository.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

Step 7: Create List, Edit, Delete and details page against EmployeeController.
Create a list view

1-List

Index.cshtml

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.FatherName) @Html.DisplayNameFor(model => model.MotherName) @Html.DisplayNameFor(model => model.Designation) @Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.FatherName) @Html.DisplayFor(modelItem => item.MotherName) @Html.DisplayFor(modelItem => item.Designation) @Html.DisplayFor(modelItem => item.Dept) @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })

Create Edit View
Create edit view as like list view and choose edit template for that.
_CreateOrEdit.cshtml

@model GenericRepo.Models.Employee

    
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.FatherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.MotherName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.MotherName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.MotherName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Dept, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Dept, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Dept, "", new { @class = "text-danger" })


Edit.cshtml

@model GenericRepo.Models.Employee


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    

Employee


@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.Partial("_CreateOrEdit", Model)
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Create Delete View
Create delete view as like list view and choose delete template for that.
Delete.cshtml

@model GenericRepo.Models.Employee

Are you sure you want to delete this?

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.FatherName)
@Html.DisplayFor(model => model.FatherName)
@Html.DisplayNameFor(model => model.MotherName)
@Html.DisplayFor(model => model.MotherName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(model => model.Dept)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Create Details View
Create details view as like list view and choose details template for that.
Details.cshtml

@model GenericRepo.Models.Employee

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.FatherName)
@Html.DisplayFor(model => model.FatherName)
@Html.DisplayNameFor(model => model.MotherName)
@Html.DisplayFor(model => model.MotherName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(model => model.Dept)

@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index")

Step 8: Add a link “Employee” to _Layout page like below

         

Step 9: Write following command in package manager console
PM> Enable-Migrations -ContextTypeName GenericRepoContext
PM> Add-Migration initalcreate
PM> Update-Database -Verbose -Force

Now your project is ready. Run application and execute CRUD operation on it. Output of the application like below.
Output:

2

Decorator Design Pattern with C#

You who work on design pattern must familiar with Gang of Four (GoF). Design Patterns: Elements of Reusable Object-Oriented Software is a Software Engineering book. The authors of this book are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The authors of this book are often refers to as Gang of Four (GoF). It’s a parody relating to Mao’s Gang of Four. This book describes the recurring solution of common problem in software design. The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Factory Pattern, Abstract Factory Pattern, Singleton Pattern, Builder e.t.c are creational design pattern. Decorator, Adapter, Bridge, Façade, Proxy, Composite e.t.c are structural design pattern. Command, interpreter, strategy, iterator e.t.c are behavioral design pattern.

Decorator Design Pattern
Decorator Design Pattern is a structural design pattern. It is also known as wrapper. It is used to add additional functionality to a particular object during run time without affecting other objects. Responsibility can be adding or removing at run time. Critics says that it uses lot of little object of similar type.

Let’s consider a scenario in which I am going to implement Decorated Design Pattern. We, Bangladeshi are very much cricket loving. A cricket equipment shop declared some package on the occasion of Cricket World Cup 2011. The base package is with a bat and a ball and its cost is 1500 Taka (Bangladeshi Currency). The smart package is with a bat, a ball and 6 stamps i.e base package plus 6 stamps and its cost is 1500 + 600 = 2100 Taka. The special package is with a bat, a ball, 6 stamps and a pair of gloves i.e smart package plus a pair of gloves. It’s cost is 2100 + 500 = 2600 Taka. It looks like the following figure. Actually, the top one wrapped the inner packages.

BlockDiagramDP

Before going to implement the scenario by decorated design pattern, I would like to show you the class diagram. The class diagram is given below.

DP_Class Diagram

Implementation: Let’s implement decorated design pattern by C#.

Step 1: Create interface ICricketInstrument for all package of cricket instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Interface for Cricket Instrument
/// Developed by: Mahedee
///

public interface ICricketInstrument
{
double Cost { get; }
string Insturments { get; }
}
}

Step 2: Create a base type for Concrete Cricket Instrument Package and Instrument Package Option

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Base type for concrete cricket instrument package and decorator(option).
/// Developed by: Mahedee
///

public abstract class CricketInstrument : ICricketInstrument
{
private double cost = 00;
private string instrument = "Cricket Instruments: ";

#region ICricketInstrument Members

public virtual double Cost
{
get { return cost; }
}

public virtual string Insturments
{
get { return instrument; }
}

#endregion
}
}

Step 3: Create a base type for Concrete Cricket Instrument Package Option. It is actually decorator – to decorate Instrument package.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace DecoratorPattern
{
    /// 
    /// Decorator for concrete package option
    /// 
    public abstract class PackageOption : CricketInstrument
    {
        double cost = 00;
        string instruments = "Abstract Package Option";

        public override double Cost
        {
            get { return cost; }
        }


        public override string Insturments
        {
            get { return instruments; }
        }

    }
}

Step 4: Create base package of Cricket Instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Base Cricket Insturment Package
///

public class BasePackage : CricketInstrument
{
double cost = 1500;
string instruments = "Ball and Bat";

public override double Cost
{
get { return cost; }
}

public override string Insturments
{
get { return base.Insturments + instruments; }
}

}
}

Step 5: Decorate Smart package for Cricket Instrument

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Smart Package = Base Package (Bat, Ball) + 6 Stamps
/// Developed by: Mahedee
///

public class SmartPackage : PackageOption
{
double cost = 600;
string instruments = "6 Stamps";
CricketInstrument objCricketInstrument;

public SmartPackage(CricketInstrument objPCricketInstrument)
{
objCricketInstrument = objPCricketInstrument;
}

public override double Cost
{
get { return objCricketInstrument.Cost + cost; }
}

public override string Insturments
{
get { return objCricketInstrument.Insturments + ", " + instruments; }
}
}
}

Step 6: Decorate Special Package for Cricket Instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
///
/// Special Package = Base Package (Bat, Ball) + 6 Stamps + 1 Pair - Gloves
/// Developed by: Mahedee
///

public class SpecialPackage : PackageOption
{
double cost = 500;
string instruments = "Gloves - 1 Pair";
CricketInstrument objCricketInstrument;

public SpecialPackage(CricketInstrument objPCricketInstrument)
{
objCricketInstrument = objPCricketInstrument;
}

public override double Cost
{
get { return objCricketInstrument.Cost + cost; }
}

public override string Insturments
{
get { return objCricketInstrument.Insturments + ", " + instruments; }
}

}
}

Step 7: Program class to create base package and decorate other package with option.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
public class Program
{
static void Main(string[] args)
{
//Base Insturment class

CricketInstrument objCricketInstruments = new BasePackage();
Console.WriteLine("::Base Package::");
Console.WriteLine(objCricketInstruments.Insturments);
Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

Console.WriteLine();

//Smart Package
objCricketInstruments = new SmartPackage(objCricketInstruments);
Console.WriteLine("::Smart Package::");
Console.WriteLine(objCricketInstruments.Insturments);
Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

Console.WriteLine();

//Special Package
objCricketInstruments = new SpecialPackage(objCricketInstruments);
Console.WriteLine("::Special Package::");
Console.WriteLine(objCricketInstruments.Insturments);
Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

Console.ReadLine();

}
}
}

Singleton Design Pattern with C#

Design Pattern

Design pattern is a solution of known problems. These are strategies of solving commonly occurring problems. A design pattern is not a finish design. It is like a template to solve a problem.

Singleton Design Pattern

Singleton is a software design pattern. It is restrict to create object more than once. This is actually needed when one object can perform its action in whole system. We frequently use a database connection object to connect with database. We don’t need multiple objects to create connection with database and close it. We can use singleton in this scenario.

Implementation of Singleton by C#

Step 1: Create EmployeeInfo class

This class is to hold employee information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
public class EmployeeInfo
{
public string EmpName { get; set; }
public string EmpDesignation { get; set; }
public int MonthlySalary { get; set; }
}
}

Step 2: Create a singleton class

Here EmployeeService is a singleton class. Constructor of this class is private so that nobody can create its instance from outside.  Instance() is a static method which creates instance of the singleton class. It actually forces that only one instance of the object will be created. Lock() is used to create instance of the singleton pattern in thread safe manner in multi threaded environment. The other two methods are used to add employee information in list and get employee salary. These two are as usual method.Don’t mix up Singleton class and Static class. Keep in mind; in static class everything must be static like Method, constructor, properties. But in singleton class it is not required. Hope, you will be clear after the following example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
///
/// EmployeeService is a singleton class
///

public class EmployeeService
{

//Static object of singleton class
private static EmployeeService instance;

private List lstEmployeeInfo = null;

///
/// Restrict to create object of Singleton class
///

private EmployeeService()
{
if (lstEmployeeInfo == null)
{
lstEmployeeInfo = new List();
}
}

///
/// The static method to provide global access to the singleton object.
///

/// Singleton object of EmployeeService class
public static EmployeeService Instance()
{

if (instance == null)
{
//Thread safe singleton

lock (typeof(EmployeeService))
{
instance = new EmployeeService();
}
}

return instance;
}

///
/// Add employee information to the Employee information list
///

///

public void AddEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
lstEmployeeInfo.Add(objEmployeeInfo);
}

///
/// Get Salary by Name
///

////// Salary of Employee

public int GetEmployeeSalaryByName(string name)
{
int monthlySalary = 0;
foreach (EmployeeInfo objEmployeeInfo in lstEmployeeInfo)
{
if (objEmployeeInfo.EmpName.Contains(name))
monthlySalary = objEmployeeInfo.MonthlySalary;
}
return monthlySalary;
}

}
}

Step 3: Access singleton class

This class creates an instance of singleton class by EmployeeService objEmployeeService = EmployeeService.Instance(); and access singleton class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
class Program
{
static void Main(string[] args)
{
EmployeeInfo objEmpInfo1 = new EmployeeInfo() { EmpName = "Mahedee", EmpDesignation = "Senior Software Engineer", MonthlySalary = 00000 };
EmployeeInfo objEmpInfo2 = new EmployeeInfo() { EmpName = "Kamal", EmpDesignation = "Software Engineer", MonthlySalary = 30000 };

//Create a singleton object
EmployeeService objEmployeeService = EmployeeService.Instance();

objEmployeeService.AddEmployeeInfo(objEmpInfo1);
objEmployeeService.AddEmployeeInfo(objEmpInfo2);

Console.WriteLine(objEmpInfo2.EmpName + " : " + objEmployeeService.GetEmployeeSalaryByName("Kamal"));

Console.ReadLine();

}
}
}

Iterator Design Pattern with C#

Iterator pattern is a design pattern which is used to traverse aggregate object often called container and access container’s object without exposing it’s underlying representation. Iterator pattern decoupled algorithm from aggregate object or container. In some cases, algorithms are container specific. We often use collection in C# and then we traverse the collection without knowing it’s internal details. Collection is grouping of some object. Objects can be same type or different type. Collection in fact actively used iterator pattern.

UML_Iterator

The above figure is UML class diagram for Iterator Pattern. The main idea behind the iterator pattern is to take the responsibility of traversing container and put it to the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and track for the next item to iterate.

Benefits:

  1. Access element of container without exposing it’s internal details.
  2. Provides a uniform interface for traversing different collection (aggregate object).
  3. Provides multiple simultaneous traversals in a collection.

Implementation:

Let’s come to the point. We are going to implement iterator design pattern. I am using here a collection for fruits item. The main actor in here:

IIterator – Interface to define Iterator (Concrete iterator class)

Iterator – Concrete iterator class which is used to iterate elements.

ICollection – Interface to define aggregate.

Collection – Concrete aggregate class.

I used FruitItem class as item class here.

Step 1: Create Item class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Item class
///

public class FruitItem
{
public string Id { get; set; }
public string Name { get; set; }
}

}

Step 2: Create IIterator Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Interface for Iterator
///

public interface IIterator
{
FruitItem First();
FruitItem Next();
FruitItem CurrentItem { get; }
bool IsDone { get; }
}
}

Step 3: Create concrete Iterator class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Concrete Iterator Class
///

public class Iterator : IIterator
{

private Collection collection;
private int current = 0;
private int step = 1;

public Iterator(Collection vCollection)
{

this.collection = vCollection;

}

public FruitItem First()
{
current = 0;
return (FruitItem)collection[current];
}

public FruitItem Next()
{
current ++;

if (!IsDone)
return (FruitItem)collection[current];
else
return null;
}

public bool IsDone
{
get { return current >= collection.Count; }
}

public FruitItem CurrentItem
{
get { return (FruitItem) collection[current]; }
}

// Gets or sets stepsize
public int Step
{
get { return step; }
set { step = value; }

}

}
}

Step 4: Create collection interface.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
///
/// Interface for Aggregate class
///

public interface ICollection
{
Iterator CreateIterator();
}
}

Step 5: Create concrete collection class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace IteratorPattern
{
///
/// Concrete aggregate class
///

public class Collection : ICollection
{
private ArrayList lstFoodItem = new ArrayList();

public Iterator CreateIterator()
{
return new Iterator(this);
}

// Get counted items
public int Count
{
get
{
return lstFoodItem.Count;
}

}

// Indexer

public object this[int index]
{

get { return lstFoodItem[index]; }

set { lstFoodItem.Add(value); }

}
}
}

Step 6: Create client class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
class Program
{
public static void Main(string[] args)
{
Collection collection = new Collection();

collection[0] = new FruitItem() { Id = "1", Name = "Mango" };
collection[1] = new FruitItem() { Id = "2", Name = "Orange" };
collection[2] = new FruitItem() { Id = "3", Name = "Banana" };
collection[3] = new FruitItem() { Id = "4", Name = "Apple" };
collection[4] = new FruitItem() { Id = "5", Name = "Lichi" };
collection[5] = new FruitItem() { Id = "7", Name = "Tamarind" };

// Create iterator
Iterator iterator = new Iterator(collection);
Console.WriteLine("Items by iterating over collection");

for (FruitItem item = iterator.First(); !iterator.IsDone; item = iterator.Next())
{
Console.WriteLine(item.Name);
}

Console.ReadLine();
}
}
}

Output:

output