Thursday, March 21, 2013

How to implement Dependency Injection in MVC



Introduction

In This article describes the, How to implement Dependency Injection in MVC. Dependency Injection is allows for easier TDD and Dependency Injection used avoid tight coupling.

How can we do this?  We do this in five steps.

Step1: Add Model class
Step2: Add data access class
Step3: Create UnityDepentacyReslover
Step4: Configure the Global.asax
Step5: Add Controller

Let's we create a simple MVC application named as DependencyInjectionPOC.

Step1: Add Model class

Let's we create a new model class name as "Student", it's a DTO (Data Transfer Object) class used to transfer data across multiple layers of an application. Just look at this code in bellow.

     public class Student
    {
        public int StudentId;
        public string StudentName;
    }

Step2: Add data access class

We create an Interface named as "IStudentRepository”. Interface can have multiple methods weather we have simply used only one method. In this time your mind has ask some question, why we would create Interface. We want swap the mock class (Used to define TDD) so only we used Interface.  How to swap the class?  I will be describe in to next blog


  public interface IStudentRepository
    {
        void AddStudents(Student student);
    }

Then we create a data access class named as "Student Repository". This class must be inherited into IStudentRepository Interface then we implement the Interface method in to "StudentRepository" class as shown in the following code

  public class StudentRepository : IStudentRepository
    {
        public void AddStudents(Student student)
        {
            List<Student> StudentList = new List<Student>();
            StudentList.Add(student);
        }
    }


Step3: Create UnityDepentacyReslover

Let's we create a class named as "UnityDepentacyReslover". This implementation will accept an IUnityContainer and will use this container for resolving the requested types. If the DependencyResolver is unable to resolve a type, it should always return null for the GetService method and an empty collection for the GetServices method. That is why a try catch is used in the UnityDependencyResolver.

   public class UnityDepentacyReslover : IDependencyResolver
    {
        IUnityContainer Container;

        public UnityDepentacyReslover(IUnityContainer Container)
        {
            this.Container = Container;
        }
        public object GetService(Type ServiceType)
        {
            try
            {
                return Container.Resolve(ServiceType);
            }
            catch
            {
                return null;
            }
        }
        public IEnumerable<object> GetServices(Type ServiceType)
        {
            try
            {
                return Container.ResolveAll(ServiceType);
            }
            catch
            {
                return null;
            }

        }
                       
    }

Step4: Configure the Global.asax

Let's we create a class name as "UnityConfig". This class is used to configure the UnityContainer.

  public class UnityConfig
    {
        public static void RegisterUnityContainer()
        {
           // A simple, extensible dependency injection container.
            UnityContainer container = new UnityContainer();
            //RegisterType a type mapping with the container, where the created instances
            container.RegisterType<IStudentRepository, StudentRepository>();
            DependencyResolver.SetResolver(new UnityDepentacyReslover(container));
        }
    }

Then call the above method into Global.asax , in the Application_Start method. Like

     protected void Application_Start()
        {
            UnityConfig.RegisterUnityContainer();
           
        }

Step5: Add Controller

Then we create a new controller named as "StudentController"

   public class StudentController : Controller
    {
        [Dependency]
        public IStudentRepository repository { get; set; }

        public ActionResult Index(Student student)
        {
            repository.AddStudents(student);
            return View();
        }

    }

Conclusion

This post is used to, How to implement Dependency Injection in MVC

No comments:

Post a Comment