Friday, January 22, 2016

Dependency Injection - Intro

This gonna be post series which I gonna continue .. Because this is bit complex and without theoretical part hard to understand.

Fist thing first.. Lets move with theoretical background of it with this post

 Assume this scenario.. - Entire Post sequence will use  this as example
There is student registration system we need to develop solution for student registration  

Here is our usual MVC code.


public class Student
   {
       public int StudentId { getset; }
       public string StudentName { getset; }
       public string RegId { getset; }
       public int Age { getset; }
 
 
       public IEnumerable<Student> GetStudents()
       {
           return new List<Student>();
       }
   }
 
Model Class 
 
public class StudentController : Controller
    {
        private readonly Student _student;
        public StudentController()
        {
            _student = new Student();
        }
        // GET: /<controller>/
 
        public IActionResult Index()
        {
            var data = _student.GetStudents();
            return View(data);
        }
    }
Controller Class 


In this way Model and controller is tightly coupled ( change of one class will effect other ) .  This way is not good in large scale projects a importantly. ( not recommend in any case )

You can find advantages and disadvantages of tight coupled code in OOP concepts.






  Dependency Injection


Dependency injection is the best way to create loose coupled code and resolve dependencies among the  classes .

In dependency injection some other class is responsible for injecting the dependencies in to client class(ex: Student Controller) we called it injector class at application run time.


here is object Diagram of it




Here is code how its look like with DI

public class Student:IStudent
   {
       public IEnumerable<Student> GetStudents()
       {
           return new List<Student>();
       }
   }
 
   public interface IStudent
   {
       IEnumerable<Student> GetStudents();
   }



public class StudentController : Controller
    {
        private readonly IStudent _student;
        public StudentController(IStudent student)
        {
            _student = student;
        }
        // GET: /<controller>/
 
        public IActionResult Index()
        {
            var data = _student.GetStudents();
            return View(data);
        }
    }
 
Enjoy Coding .. next post is on the way

1 comments:

Tanvir Ahmmed said...

Thank you for sharing this insightful article! Your thoughtful perspective and valuable information greatly enrich the community. We appreciate your dedication to knowledge sharing. Well done! Read more What is IoT?