Click here to Skip to main content
15,171,439 members
Articles / Programming Languages / C#
Article
Posted 4 Aug 2013

Tagged as

Stats

65.3K views
21 bookmarked

Microsoft Unity in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.97/5 (16 votes)
4 Aug 2013CPOL2 min read
Applying dependency injection and inversion of control in ASP.NET MVC with Microsoft Unity

Introduction

One way for decoupling classes is using Unity. You can learn more about Unity here. In this article, I will try to describe the usage of Unity. For doing that, you should follow the steps below.

Using Code

  1. Create a new project in Visual Studio (Visual Studio 2012 recommended)
    1. In File menu, click New -> Project.
    2. In New Project window, select Visual C# -> Web and then select ASP.NET MVC 4 Web Application. Figure a-1.
    3. Name the project (e.g. TestUnity).
    4. Click OK button.
    5. In New ASP.NET MVC 4 Project window, select Internet Application and Razor View engine (creating unit test project is optional ). Figure a-2.
    6. Click OK button.
  2. New Project Window

    Figure a-1: Create a new project in Microsoft Visual Studio 2012.

    New ASP.NET MVC 4 Project Window

    Figure a-2: Select Internet Application and Razor view engine.

    After step A, your project has been created and is ready for programming. Now you should install Unity as below (step B).

  3. Installing Microsoft Unity
    1. In solution explorer window, right click on References folder.
    2. Click Manage NuGet Packages (don’t forget you have to connect to the internet).
    3. In left panel of Manage NuGet Packages window, select Online.
    4. In Search box placed in right panel of Manage NuGet Packages window, type unity3.
    5. In list of search result, select Unity bootstrapper for ASP.NET MVC and click install (click Accept button if it wants). After some moments, Unity will be installing. Figure b-1.
    6. Click close button to close Manage NuGet Packages window.
  4. Manage NuGet Packages Window

    Figure b-1: Install Unity bootstrapper for ASP.NET MVC.

    Unity will add two classes into App_Start folder (UnityConfig.cs, UnityMvcActivator.cs).

  5. Create a class in Models folder named Person as follows:
    1. Right click on Models folder and select Add -> Class
    2. Name the class Person.cs
    3. Type the below code into Person class:
  6. C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;
    
    namespace TestUnity.Models
    {
        public class Person
        {
            [ScaffoldColumn(false)]
            public int Id { get; set; }
    
            [Required]
            public string Name { get; set; }
    
            public int Age { get; set; }
    
            [Display(Name = "Contact Information")]
            public string ContactInfo { get; set; }
        }
    }
    
  7. Create WSCDBProvider class into Models folder as follows:
    1. Right click on Models folder and select Add->Class
    2. Name the class WSCDBProvider.cs
    3. Type the following code into WSCDBProvider.cs class
  8. C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using System.Data.Entity;
    
    namespace TestUnity.Models
    {
        public class WSCDBProvider : DbContext
        {
            public DbSet<person> Persons { get; set; }
        }
    }
    
  9. Create an interface in Models folder named IPersonRepository:
    1. Right click on Models folder and select Add -> Class
    2. In items list, select Interface and named it IPersonRepository.cs
    3. Click Add button
    4. Type the following code into IPersonRepository interface:
  10. C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using TestUnity.Models;
    
    namespace TestUnity.Models
    {
        public interface IPersonRepository : IDisposable
        {
            IEnumerable<person> GetAll();
            void InsertorUpdate(Person contact);
            Person Find(int id);
            bool Delete(int id);
            void Save();
        }
    }
    
  11. Create a class in Models folder named PersonRepository as follows:
    1. Right click on Models folder and select Add -> Class
    2. Name the class PersonRepository.cs
    3. Type the following code into class:
  12. C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using System.Data;
    
    namespace TestUnity.Models
    {
        public class PersonRepository : IPersonRepository
        {
            private WSCDBProvider db = new WSCDBProvider();
    
            public IEnumerable<person> GetAll()
            {
                return db.Persons.ToList();
            }
    
            public Person Find(int id)
            {
                return db.Persons.Find(id);
            }
    
            public bool Delete(int id)
            {
                try
                {
                    Person person = Find(id);
                    db.Persons.Remove(person);
                    Save();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            public void InsertorUpdate(Person person)
            {
                if (person.Id == default(int))
                {
                    // New entity
                    db.Persons.Add(person);
                }
                else
                {
                    // Existing entity
                    db.Entry(person).State = EntityState.Modified;
                }
            }
    
            public void Save()
            {
                db.SaveChanges();
            }
    
            public void Dispose()
            {
                db.Dispose();
            }
    
        }
    }
    
  13. Creating Person Controller:
    1. Right click on Controller folder and select Add -> Controller
    2. In Add Controller window, name controller PersonController
    3. For Scaffolding options, select MVC controller with empty read/write actions
    4. Click Add button. Figure g-1.
    5. Change the controller code as shown below:
  14. Manage NuGet Packages Window

    Figure g-1 : Add Controller
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using TestUnity.Models;
    
    namespace TestUnity.Controllers
    {
        public class PersonController : Controller
        {
            private readonly IPersonRepository repository;
    
            public PersonController(IPersonRepository repository)
            {
                this.repository = repository;
            }
    
            public ActionResult Index()
            {
                var persons = repository.GetAll();
                return View(persons);
            }
    
            public ActionResult Details(int id)
            {
                var person = repository.Find(id);
                return View(person);
            }
    
            public ActionResult Create()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult Create(Person person)
            {
                try
                {
                    repository.InsertorUpdate(person);
                    repository.Save();
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            public ActionResult Edit(int id)
            {
                var person = repository.Find(id);
                return View(person);
            }
    
            [HttpPost]
            public ActionResult Edit(int id, Person model)
            {
                try
                {
                    var person = repository.Find(id);
                    repository.InsertorUpdate(person);
                    repository.Save();
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            public ActionResult Delete(int id)
            {
                var person = repository.Find(id);
                return View(person);
            }
    
            [HttpPost, ActionName("Delete")]
            public ActionResult DeleteConfirmed(int id)
            {
                bool ret = repository.Delete(id);
                if(ret)
                    return RedirectToAction("Index");
                return View();
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    repository.Dispose();
                }
                base.Dispose(disposing);
            }
        }
    }
    
  15. Now you should use Unity for injecting repository into Controller.
    1. Open UnityConfig.cs class from App_Start folder
    2. Type injecting command in RegisterTypes method as shown below:
  16. C#
    container.RegisterType<IPersonRepository, PersonRepository>();
    

    Manage NuGet Packages Window

    Figure h-1 : UnityConfig.cs class
  17. Now your project is ready for creating Views and Run and Use.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Radmehr Hassanizadeh
Iran (Islamic Republic of) Iran (Islamic Republic of)
No Biography provided

Comments and Discussions

 
QuestionMVC 5 with Unity for Dependency Injection Pin
itsaranga23-Apr-15 19:32
Memberitsaranga23-Apr-15 19:32 
Thanks for the great article Radmehr.

If anyone interested on Unity.Mvc5 package please refer MVC 5 with Unity for Dependency Injection
GeneralMy vote of 5 Pin
Humayun Kabir Mamun11-Nov-14 1:06
MemberHumayun Kabir Mamun11-Nov-14 1:06 
GeneralMy vote of 5 Pin
Mohit-Nagarro27-Aug-14 22:04
MemberMohit-Nagarro27-Aug-14 22:04 
SuggestionHttpPost Edit need to be changed Pin
Mohit-Nagarro27-Aug-14 22:03
MemberMohit-Nagarro27-Aug-14 22:03 
AnswerRe: HttpPost Edit need to be changed Pin
Radmehr Hassanizadeh30-Nov-14 16:42
MemberRadmehr Hassanizadeh30-Nov-14 16:42 
QuestionMy vote of 5 Pin
hasanfar28-Mar-14 5:49
Memberhasanfar28-Mar-14 5:49 
GeneralMy vote of 5 Pin
nodar22-Sep-13 17:27
Membernodar22-Sep-13 17:27 
QuestionVS 2012 not to be recommended Pin
Akhil Mittal4-Aug-13 20:17
professionalAkhil Mittal4-Aug-13 20:17 
GeneralMy vote of 4 Pin
Akhil Mittal4-Aug-13 20:14
professionalAkhil Mittal4-Aug-13 20:14 
GeneralRe: My vote of 4 Pin
Radmehr Hassanizadeh6-Aug-13 13:41
MemberRadmehr Hassanizadeh6-Aug-13 13:41 
QuestionWhy VS2012? Pin
Vitaly Tomilov4-Aug-13 15:17
MemberVitaly Tomilov4-Aug-13 15:17 
AnswerRe: Why VS2012? Pin
Radmehr Hassanizadeh6-Aug-13 13:46
MemberRadmehr Hassanizadeh6-Aug-13 13:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.