Introduction
Most of the projects which are created with dependency are not good for Maintenance because the people which have developed that project are moved to a new project or have left the organization and there is no proper documentation of project which creates problem while maintaining the project. At the means, while there is some change in that project which is to be done fast it creates problem to understand the code. To resolve this kind of problem we are going use Microsoft Unity Framework which will help us to make the project easy to maintain.
"The good project is always easy for Maintenance"
What is Dependency injection?
Dependency injection is a design pattern which is used to remove hard code dependency.
Types of Injection
- Constructor Injection
- Property Setter Injection (Properties)
- Method Injection
We are going to use Constructor Injection in this article because this type is mostly used.
Tools Required.
Visual Studio 2015
SQL Server 2008
Let’s start with creating an MVC Project using Basic Project Template.
Creating Application
Open visual studio IDE on start page select New Project …
Fig 1. Start page
After selecting New Project link a New Project Dialog will Appear Inside that select Templates -> Visual C# inside this select Web after selecting you will see "ASP.NET Web Application" after selecting just name your Project as "MvcInjection" and finally click on OK button to create project.
Selecting Templates
Fig 2. Selecting Template
After clicking on the ok button then another project template selection wizard will pop up with Name "New ASP.NET Project" in this template select MVC Template and we are not going to Create Unit testing for this project hence do not check this option and finally click on OK button.
Fig 3. Selecting MVC Project
After selecting all option as told above now click the OK button your Project will be created.
Project structure after creating MvcInjection project
Fig 4. Project structure
After Creating Project now we are going add Layer in the project [Class library].
Adding MVCInjection.Model [Class library]
First, we are going to add a Model layer with name MVCInjection.Model
Layer.
Tips: You might think that we have a Model folder in the project still why we are adding MVCInjection.Model
layer because if we have a large project it is better to Move Model in to [Class library] and added a reference to the main project.
To add [Class library] just right click on your project from List select Add -> then select New Project.
Fig 5.Steps to add Class library
After selecting New Project a new dialog will pop up with name Add new Project from lets panel select type Visual C# inside that select Windows and from template select [Class Library] and then name your project as MVCInjection.Model
and click on Ok button.
Fig 6. Adding MVCInjection.Model [Class library]
Project structure after Adding MVCInjection.Model
Now we are going to Add Interface to make your application loose couple.
Adding MVCInjection.Interface [Class library]
We are going to add MVCInjection.Interface
in a similar way as we have Added MVCInjection.Model
[Class library].
To add [Class library] just right click on your project from List select Add -> then select New Project.
After selecting New Project a new dialog will pop up with name Add new Project from lets panel select type Visual C# inside that select Windows and from template select [Class Library] and then name your project as MVCInjection.Interface
and click on Ok button.
Fig 7. Adding MVCInjection.Interface [Class library]
Project structure after Adding MVCInjection.Interface
Now we are going to Add Concrete classes which will implement Interface.
Adding MVCInjection.Concrete [Class library]
We are going to add MVCInjection.Concrete
in a similar way as we have Added MVCInjection.Interface
[Class library].
To add [Class library] just right click on your project from List select Add -> then select New Project.
After selecting New Project a new dialog will pop up with name Add new Project from lets panel select type Visual C# inside that select Windows and from template select [Class Library] and then name your project as MVCInjection.Concrete
and click on Ok button.
Fig 8. Adding MVCInjection.Concrete [Class library]
Project structure after Adding MVCInjection.Concrete
Now we have completed adding all [Class library] in the project.
Adding Model in MVCInjection.Model
Next, we are going add a model in [MVCInjection.Model] with name CustomerModel
For adding Model just Right Click on MVCInjection.Model ->Then Select Add -> inside that Select Class.
After Clicking on class Add New Item dialog will pop up with Class selection and asking for the class name here we are going to enter the class name as "CustomerModel
".
After adding Model now let’s add some properties to it.
Adding Properties to CustomerModel
namespace MVCInjection.Model
{
public class CustomerModel
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string Phoneno { get; set; }
}
}
After completing with adding model and properties now let’s add Interface.
Adding Interface in MVCInjection.Interface
We are going add interface in MVCInjection.Interface
.
For adding Interface just Right Click on MVCInjection.Interface ->Then Select Add ->inside that Select Add New Item menu.
After Clicking on Add New item a new Add New Item dialog will pop up inside that select Interface and then we going to name Interface as "ICustomer
".
Fig 9. Adding Interface in MVCInjection.Interface
After adding interface now we are going to Add Reference of MVCInjection.Model
in MVCInjection.Interface
to access Model inside interface.
Adding Reference of MVCInjection.Model (Customer) in MVCInjection.Interface (ICustomer)
To Add Reference just right Click on MVCInjection.Interface
[Class Library] then select Add Reference after select a new dialog will pop up with name Reference Manager inside that select MVCInjection.Model
and then click on OK button.
After adding Reference now we are going declare some method in the interface.
Declaring method in MVCInjection.Interface
using MVCInjection.Model;
using System.Collections.Generic;
namespace MVCInjection.Interface
{
public interface ICustomer
{
void Add(CustomerModel Customer);
void Update(CustomerModel Customer);
void Delete(CustomerModel Customer);
CustomerModel GetById(int id);
IEnumerable<CustomerModel> GetAll();
}
}
After completing with declaring all method in interface now let’s add Concrete class in MVCInjection.Concrete
.
Adding Class in MVCInjection.Concrete
We are going add a class in MVCInjection.Concrete
in [Class library] in the project.
For adding Model just Right Click on MVCInjection.Concrete ->Then Select Add -> inside that Select Class.
After Clicking on class Add New Item dialog will pop up with Class selection and asking for the class name here we are going to enter the class name as "CustomerConcrete
".
Adding Reference of MVCInjection.Interface (ICustomer) in MVCInjection.Concrete (ICustomer)
To Add Reference just right Click on MVCInjection.Concrete
[Class Library] then select Add Reference after selecting a new dialog will pop up with name Reference Manager inside that select MVCInjection.Interface
and MVCInjection.Model
both are required then click on OK button.
Now we have completed with adding Reference now let’s Implement all Method declared in ICustomer Interface in CustomerConcrete
class.
CustomerConcrete class will implement ICustomer interface.
using MVCInjection.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MVCInjection.Model;
namespace MVCInjection.Concrete
{
public class CustomerConcrete : ICustomer
{
}
}
Now to perform all database operation such as CRUD I am going to use Dapper ORM.
We are going add Reference of Dapper ORM from NuGet package manager and we are going add it in MVCInjection.Concrete
[Class Library].
To open Manage NuGet Package dialog just right click on MVCInjection.Concrete
[Class Library] and from List select Manage NuGet package.
Snapshot of Manage NuGet package dialog.
In the search box enter Dapper. And select Dapper dot net as shown in below and click on Install button.
Project structure after Adding Dapper
After adding Dapper ORM next we are Create Database and Table and Store procedure for performing CRUD operation.
Database Part
Here I am going to show some database part.
I have Created Database with the name [CustomerDB].
After that, I have created a table inside CustomerDB database with the name [CustomerTB].
We are going use store procedure for performing CRUD operation.
Below are names of stored procedure which I have created I will provide this store procedure to download.
Connection string Used
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=sai-pc;Database=CustomerDB;UID=sa;Password=Pass$123" />
</connectionStrings>
After Completing with Database part we are again going back to CustomerConcrete
class in MVCInjection.Concrete
[Class Library].
CustomerConcrete class will implement the ICustomer interface
In this part, I am implementing all method which is declared in the interface and using Dapper to perform Crud operation.
using Dapper;
using MVCInjection.Interface;
using MVCInjection.Model;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace MVCInjection.Concrete
{
public class CustomerConcrete : ICustomer
{
public void Add(CustomerModel Customer)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
con.Open();
SqlTransaction sqltans = con.BeginTransaction();
var param = new DynamicParameters();
param.Add("@CustomerID", Customer.CustomerID);
param.Add("@Name", Customer.Name);
param.Add("@Address", Customer.Address);
param.Add("@Country", Customer.Country);
param.Add("@City", Customer.City);
param.Add("@Phoneno", Customer.Phoneno);
var result = con.Execute("sprocCustomerTBInsertUpdateSingleItem",
param,
sqltans,
0,
commandType: CommandType.StoredProcedure);
if (result > 0)
{
sqltans.Commit();
}
else
{
sqltans.Rollback();
}
}
}
catch (System.Exception)
{
throw;
}
}
public void Update(CustomerModel Customer)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
con.Open();
SqlTransaction sqltans = con.BeginTransaction();
var param = new DynamicParameters();
param.Add("@CustomerID", Customer.CustomerID);
param.Add("@Name", Customer.Name);
param.Add("@Address", Customer.Address);
param.Add("@Country", Customer.Country);
param.Add("@City", Customer.City);
param.Add("@Phoneno", Customer.Phoneno);
var result = con.Execute("sprocCustomerTBInsertUpdateSingleItem",
param,
sqltans,
0,
commandType: CommandType.StoredProcedure);
if (result > 0)
{
sqltans.Commit();
}
else
{
sqltans.Rollback();
}
}
}
catch (System.Exception)
{
throw;
}
}
public void Delete(CustomerModel Customer)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
con.Open();
SqlTransaction sqltans = con.BeginTransaction();
var param = new DynamicParameters();
param.Add("@CustomerID", Customer.CustomerID);
var result = con.Execute("sprocCustomerTBDeleteSingleItem",
param,
sqltans,
0,
commandType: CommandType.StoredProcedure);
if (result > 0)
{
sqltans.Commit();
}
else
{
sqltans.Rollback();
}
}
}
catch (System.Exception)
{
throw;
}
}
public CustomerModel GetById(int id)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
con.Open();
var param = new DynamicParameters();
param.Add("@CustomerID", id);
return con.Query<CustomerModel>("sprocCustomerTBSelectList",
param,
null,
true,
0,
commandType: CommandType.StoredProcedure).SingleOrDefault();
}
}
catch (System.Exception)
{
throw;
}
}
public IEnumerable<CustomerModel> GetAll()
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
con.Open();
var param = new DynamicParameters();
return con.Query<CustomerModel>("sprocCustomerTBSelectList",
null,
null,
true,
0,
commandType: CommandType.StoredProcedure).ToList();
}
}
catch (System.Exception)
{
throw;
}
}
}
}
After completing with implementing next we are going to add reference of Model and Interface in Main web Project [MvcInjection].
Adding Reference of Model and Interface to Main Web Project MvcInjection
To Add Reference just right Click on MVCInjection then select Add Reference after select a new dialog will pop up with name Reference Manager inside that select MVCInjection.Interface
, MVCInjection.Model
, MVCInjection.Concrete
which is required then click on OK button.
Reference after adding in Project
After adding this reference now let’s Add a Controller with name CustomerController
Adding Controller
For adding Controller Just Right click on Controller Folder inside that select Add and then select Controller.
After clicking on Controller new dialog will pop up with name Add Controller.
I will name Controller as "CustomerController" and in Template, I will choose "MVC controller with empty read/write actions" and finally click on Add button.
Project Structure after Adding CustomerController
CustomerController with all Empty Action Method
Now we are going to add reference of Microsoft Unity Framework to MVCInjection Application.
Adding Microsoft Unity Framework Reference
There are 2 ways of adding Microsoft Unity Framework
- Adding Using Manage NuGet package
To open Manage NuGet Package dialog just right click on MVCInjection and from List select Manage NuGet package.
In the search box enter Unity.
And select Unity as shown in below and click on Install button it will get installed.
After adding Unity next we are going to add Unity.MVC package to project as same we have Added Unity, just in the search box enter Unity.MVC and select Unity.MVC as show in below and click on Install button it will get installed.
After Installing Microsoft Unity Framework you should able to see 2 classes UnityConfig
class and UnityWebActivator
class in Application start folder [App_Start].
Project Structure after Adding Microsoft Unity Framework
After installing Microsoft Unity Framework you will find 2 classes UnityConfig
and UnityWebActivator
.
UnityConfig
: Specifies the Unity configuration for the main container.
UnityWebActivator
: Provides the bootstrapping for integrating Unity with ASP.NET MVC.
Below you can see a snapshot of UnityConfig
classes.
Register
Now we are going registers all the type mappings with the Unity container.
In UnityConfig
class we are going to use RegisterTypes
Method in this method we are going keep mapping to which Interface the concrete class should resolve.
private readonly ICustomer ICustomer;
public CustomerController(ICustomer _ICustomer)
{
this.ICustomer = _ICustomer;
}
We have one interface with name ICustomer
and other Concrete
class with name CustomerConcrete
we are registering Type in Unity container.
Here we have Registered Type.
container.RegisterType<ICustomer, CustomerConcrete>();
We should register all types in RegisterTypes
Method only.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<ICustomer, CustomerConcrete>();
}
This indicates that where ever we are using ICustomer
for constructor injection there it should inject CustomerConcrete
object.
Now we do not require create object all object creation will be handled by Unity container rather you ask the Unity container to do it for you so that the container can resolve any dependencies.
Now we are going to Use constructor injection we are going to do this in CustomerController
.
private readonly ICustomer ICustomer;
public CustomerController(ICustomer _ICustomer)
{
this.ICustomer = _ICustomer;
}
At the run time while your constructor gets invoke at that time Unity container will resolve ICustomer interface with CustomerConcrete
Class.
Now from constructor injection, we are getting object than from this object we can call all methods of CustomerConcrete
Class.
Below is code snippet of CustomerController
.
using MVCInjection.Interface;
using MVCInjection.Model;
using System.Web.Mvc;
namespace MvcInjection.Controllers
{
public class CustomerController : Controller
{
private readonly ICustomer ICustomer;
public CustomerController(ICustomer _ICustomer)
{
this.ICustomer = _ICustomer;
}
public ActionResult Index()
{
var Alldata = ICustomer.GetAll();
return View(Alldata);
}
public ActionResult Details(int id)
{
var Detailsdata = ICustomer.GetById(id);
return View(Detailsdata);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(CustomerModel Customer)
{
try
{
if (ModelState.IsValid)
{
ICustomer.Add(Customer);
return View();
}
else
{
return View(Customer);
}
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
var Editdata = ICustomer.GetById(id);
return View(Editdata);
}
[HttpPost]
public ActionResult Edit(CustomerModel Customer)
{
try
{
if (ModelState.IsValid)
{
ICustomer.Update(Customer);
return View();
}
else
{
return View(Customer);
}
}
catch
{
return View();
}
}
public ActionResult Delete(int id)
{
var Deletedata = ICustomer.GetById(id);
return View(Deletedata);
}
[HttpPost]
public ActionResult Delete(CustomerModel Customer)
{
try
{
ICustomer.Delete(Customer);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
After completing accessing all Method of CustomerConcrete
Class with in all Action Method Using Unity constructor injection now we are going to add all View of all Action Method one by one.
Adding View of All Create / Update / Delete / Index
For Adding View just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form.
Here in below snapshot I have selected View engine as Razor and we are going to create a strongly typed view for that I have selected Model class Customer and we want to create an input form for that I have selected Create in Scaffold template finally click on Add button.
After clicking on Add button, the View will get created and it is stored in Views folder inside this folder there is a folder with same name as Controller [Customer] inside that this View will be placed.
In a similar way, we are going to Add View for all Action Method.
Adding Details View
For Adding Details View we are just going to follow the similar step in Model we are going to select Customer and in Scaffold template, we are going to select Details.
Adding Create View
For Adding Create View we are just going to follow the similar step in Model we are going to select Customer and in Scaffold template, we are going to select Create.
Adding Edit View
For Adding Edit View we are just going to follow the similar step in Model we are going to select Customer and in Scaffold template, we are going to select Edit.
Adding Delete View
For Adding Delete View we are just going to follow the similar step in Model we are going to select Customer and in Scaffold template, we are going to select Delete.
After completing adding all View your Views Folder should look like this as shown below.
Project structure after Adding Views
Now we have completed adding Views let’s to run the application.
To access application we are going to enter URL: - http://localhost:#####/Customer/create
(##### is local host port number).
Execution of Application only on the first run.
After running application we are going to see how constructor injection takes place.
By attaching a debugger at constructor you can check what is getting injected.
In below snapshot, it is injecting Concrete
class (CustomerConcrete
).
We have called Create Action method it will return a View [Create].
After entering data I am going click on Create button to save data in the database.
In a similar way, we can access all views which we have created.
"If you had looked closely the object creation process is moved Out we are No more creating object manually."
Result after Creating Customer [Sql server]