Dependency Injection Pattern

Dependency Injection : Instead of creating objects inside the class it allows you to inject objects
There are three types of injections are there 1) Construction Injection 2) Setter Injection 3) Interface Injection
Object Dependency Explained
When an object needs another object to operate properly, we say that the former is dependent on the latter. This behavior is transitive in nature. Consider three objects, namely, A, B, and C. If object A is coupled to object B, and B is in turn coupled to C, then object A is effectively coupled to object C—it is dependent on C. I've used the terms coupling and dependency interchangeably in this article.

Objects can be coupled in two ways: tight coupling and loose coupling. When an object is loosely coupled with another object, you can change the coupling with ease; when the coupling is tight, the objects are not independently reusable and hence are difficult to use effectively in unit test scenarios.

Here's an example of tight coupling. Consider two classes, C1 and C2, where C1 is tightly coupled with C2 and requires it to operate. In this case C1 is dependent on C2, as shown below:


   public class C2
   {
     //Some code
   }
   public class C1
   {
      C2 bObject = new C2();
      //Some code
   }
The tight coupling between the two classes shown above occurs because C1 (which is dependent on C2) creates and contains an instance of the class C2. It's "tight" because you can eliminate or change the dependency only by modifying the container class (C1). This is where dependency injection fits in.
What is Dependency Injection?
Dependency injection eliminates tight coupling between objects to make both the objects and applications that use them more flexible, reusable, and easier to test. It facilitates the creation of loosely coupled objects and their dependencies. The basic idea behind Dependency Injection is that you should isolate the implementation of an object from the construction of objects on which it depends. Dependency Injection is a form of the Inversion of Control Pattern where a factory object carries the responsibility for object creation and linking. The factory object ensures loose coupling between the objects and promotes seamless testability.

Advantages and Disadvantages of Dependency Injection
The primary advantages of dependency injection are:
  • Loose coupling
  • Centralized configuration
  • Easily testable
 =====================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private IDataAccess GetDataAccessFactory(string rqType)
        {
            string typeString = string.Empty;
            IDataAccess reqType = null;
           
            switch(rqType)
            {
                case  "Oracle":
                    typeString = "WindowsFormsApplication2.OracleDataAccess";
                    break;
                case "SQlServer":
                    typeString = "WindowsFormsApplication2.SqlDataAccess";
                    break;
            }

             Type xxx = Type.GetType(typeString);
            reqType = Activator.CreateInstance(xxx) as IDataAccess;

            return reqType;
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            //Type xxx = Type.GetType("WindowsFormsApplication2.SqlDataAccess");
           // Type xxx = Type.GetType("WindowsFormsApplication2.OracleDataAccess");

            //IDataAccess reqDataAccess = Activator.CreateInstance(xxx)  as IDataAccess;

            //DataAccess da = new DataAccess(Activator.CreateInstance(xxx) as IDataAccess);

            //MessageBox.Show(da.GetData());

            DataAccess da = new DataAccess(GetDataAccessFactory("Oracle"));

            MessageBox.Show(da.GetData());


            da.RequiredObject = GetDataAccessFactory("SQlServer");
            MessageBox.Show(da.GetData());

       
        }


        private DataTable GetFulfillmentOrderReleases(int fulfillmentOrderId)
        {
            SqlConnection objCon = new SqlConnection("User ID=Automation_Service;pwd=fran-fRe;Server=MNDEV02;Database=CDMS");
            SqlDataAdapter objAdp = new SqlDataAdapter("SELECT * FROM  FulfillmentOrderReleases WHERE iPK_OrderReleaseID = " + fulfillmentOrderId.ToString(),objCon);
            DataTable dt = new DataTable();
            objAdp.Fill(dt);

            return dt;
        }

        private List GetListForTable(DataTable dt) where T : new()
        {
            List reqList = new List();

            Type reqType = typeof(T);

            foreach (DataRow dr in dt.Rows)
            {

                //T reqObj = Activator.CreateInstance();
                T reqObj = new T();


                PropertyInfo[] propInfo = reqType.GetProperties();

                foreach (PropertyInfo prop in propInfo)
                {
                    prop.SetValue(reqObj, dr[prop.Name]);
                }
                reqList.Add(reqObj);
            }

            return reqList;
        }
    }

    public interface IDataAccess
    {
        string GetData();
    }


    public class DataAccess
    {
        private IDataAccess reqObject;
        public  IDataAccess RequiredObject
        {
            get
            {
                return reqObject;
            }
            set
            {
                reqObject = value;
            }

        }


        public DataAccess(IDataAccess pReqObject)
        {
            reqObject = pReqObject;
        }

        public string GetData()
        {
            return reqObject.GetData();
        }

    }

    public class SqlDataAccess : IDataAccess
    {
        public string GetData()
        {
            return "This data is comming from SQL";
        }
    }

    public class OracleDataAccess : IDataAccess
    {
        public string GetData()
        {
            return "This data is comming from Oracle";
        }
    }

    public class FulfillmentOrderReleases
    {
        public int iPK_OrderReleaseID  { get; set;}
        public int iFK_FulfillmentOrderID{get;set;}
        public int iFK_ParentOrderReleaseID { get; set; }
        public DateTime dt_DateEntered { get; set; }
        public int iFK_EnteredByID { get; set; }
        public int iFK_LocationID { get; set; }
        public DateTime dt_RequiredShipDate { get; set; }
        public int iFK_PreferredServiceLevelID { get; set; }
        public int i_Status { get; set; }
        public int b_Complete { get; set; }
        public DateTime dt_DateCompleted { get; set; }
        public string vch_PurchaseOrder { get; set; }
        public string vch_ERP_ID { get; set; }

    }


}
 

No comments:

Post a Comment