Skip to main content

Dependency Injection


Definition:

1. High level classes/modules should not depend on low-level classes/modules, both should depend on abstraction.  

2. It relates to the way in which an object obtains references to its dependencies.

3. The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.

4. Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have concrete dependencies. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.


Code Example:

Constructor Injection
This is the most commonly used dependency pattern in Object Oriented Programming. The constructor injection normally has only one parameterized constructor, so in this constructor dependency there is no default constructor and we need to pass the specified value at the time of object creation. We can use the injection component anywhere within the class. It addresses the most common scenario where a class requires one or more dependencies.
The following is an example:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace propertyinjuction  
  8. {  
  9.     public interface text  
  10.     {  
  11.         void print();  
  12.       
  13.     }  
  14.     class format : text  
  15.     {  
  16.         public void print()  
  17.         {  
  18.   
  19.             Console.WriteLine(" here is text format");  
  20.           
  21.         }  
  22.       
  23.     }  
  24.     // constructor injection  
  25.     public class constructorinjection  
  26.     {  
  27.   
  28.         private text _text;  
  29.         public constructorinjection(text t1)  
  30.         {  
  31.             this._text = t1;  
  32.           
  33.         }  
  34.         public void print()  
  35.         {  
  36.   
  37.             _text.print();  
  38.         }  
  39.   
  40.   
  41.   
  42.   
  43.       
  44.     }  
  45.     class constructor  
  46.     {  
  47.   
  48.         static void Main(string[] args)  
  49.         {  
  50.   
  51.             constructorinjection cs = new constructorinjection(new format());  
  52.             cs.print();  
  53.             Console.ReadKey();  
  54.           
  55.         }  
  56.     }  
  57. }  
By passing the services that implemented the text interface the builder assembled the dependencies.

Property Injection
We use constructor injection, but there are some cases where I need a parameter-less constructor so we need to use property injection.
The following is an example:
  1. public interface INofificationAction  
  2. {  
  3.       
  4.    void ActOnNotification(string message);  

  5. }  
  6.    class atul  
  7.    {  
  8.        INofificationAction task = null;  
  9.        public void notify(INofificationAction  at ,string messages)  
  10.        {  
  11.   
  12.        this.task = at;  
  13.        task.ActOnNotification(messages);  
  14.      
  15.      
  16.        }  
  17.      
  18.    }  
  19.    class EventLogWriter : INofificationAction  
  20.    {  
  21.        public void ActOnNotification(string message)  
  22.        {  
  23.            // Write to event log here  
  24.        }  
  25.    }  
  26.    class Program  
  27.    {  
  28.        static void Main(string[] args)  
  29.        {  
  30.            //services srv = new services();  
  31.            //other oth = new other();  
  32.            //oth.run();  
  33.            //Console.WriteLine();  
  34.            EventLogWriter elw = new EventLogWriter();  
  35.            atul at = new atul();  
  36.            at.notify(elw, "to logg");  
  37.            Console.ReadKey();  
  38.        }  
  39.    }  
You cannot control when the dependency is set at all, it can be changed at any point in the object's lifetime. 
Method Injection
In method injection we need to pass the dependency in the method only. The entire class does not need the dependency, just the one method. I have a class with a method that has a dependency. I do not want to use constructor injection because then I would be creating the dependent object every time this class is instantiated and most of the methods do not need this dependent object.
The following is an example:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace propertyinjuction  
  8. {  
  9.   
  10.     public interface Iset  
  11.     {  
  12.         void print();  
  13.       
  14.     }  
  15.     public class servic : Iset  
  16.     {  
  17.         public void print()  
  18.         {  
  19.             Console.WriteLine("print........");  
  20.           
  21.         }  
  22.       
  23.     }  
  24.     public class client  
  25.     {  
  26.         private Iset _set;  
  27.         public void run(Iset serv)  
  28.         {  
  29.   
  30.             this._set = serv;  
  31.             Console.WriteLine("start");  
  32.             this._set.print();  
  33.         }  
  34.       
  35.     }  
  36.     class method  
  37.     {  
  38.         public static void Main()  
  39.         {  
  40.             client cn = new client();  
  41.             cn.run(new servic());  
  42.             Console.ReadKey();  
  43.           
  44.           
  45.         }  
  46.     }  
  47. }  


Advantage of Dependency Injection(DI):


  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing






                                            

Comments

Popular posts from this blog

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         }     }     public class Student : IDoWork     {         public string DoWork()         {             return "Study in school" ;         }     } This class will actually create an instance of the concrete class so that you can work on that        object further     public class FactoryDemo     {         public T Create

How to enable windows authentication in PostgreSQL

1.     Steps to create user or role in PostgreSQL ·         Open pgAdmin III ·         Login to PostgreSQL database ·         Select “Login Roles” and right click on mouse to view the context menu ·         Select “New Login Role” from context menu ·         Enter desired user name in “Role name” text box ·         Select “Definition” tab in “New Login Role” window ·         Enter desired Password in the given text box ·         Select “Role privileges” tab in “New Login Role” window ·         Select the privileges for the entered user or role ·         Select “SQL” tab in “New Login Role” window ·         This will display the auto generated script ·         Review the script and click on “OK” button ·         Now in the “Login Roles” the newly created role or user “newUser” is displayed ·         Now in pgAdmin III object browser select the database to which the newly created user should be ma

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete University cl