Thursday, October 19, 2017

Dependency Injection In c#

Dependency Injection (DI) is a software design pattern that we can develop loosely couple software component. DI also enables us to better manage future changes, re-usability and other complexity in our software. When we going to develop software loosely coupling is very important concept and it gives us to more flexibility in deployment also. Simply we can say one object supplies the dependencies of another object is DI. So we are not going to create any objects of outside class using new key word inside another class.


According to the above picture Interface is very important thing in DI. All the methods that we can access through interface layer.
There are three types of Dependency Injection
  • ·         Constructor Injection
  • ·         Property Injection
  • ·         Method Injection



Let’s go through above three types with sample codes


Constructor Injection
This is the most commonly used Dependency Pattern.

This pattern is done by supplying the dependency through the class’s constructor when instantiating that class.


public interface IDataLayer
    {
        void DoDataLayerLogic();
    }

    public class DataLayer : IDataLayer
    {
        public void DoDataLayerLogic()
        {
            Console.WriteLine("Data Layer Logic Done");
        }
    }

    public class BussinessLogicLayer
    {
        private IDataLayer _dataLayer;

        public BussinessLogicLayer(IDataLayer dataLayer)
        {
            this._dataLayer = dataLayer;
        }

        public void DoBussinessLogic()
        {
            Console.WriteLine("Service Started");
            this._dataLayer.DoDataLayerLogic();
        }
    }



BulkInsert

public void InsertCaller()         {             DataSet ds = new DataSet();             ds.ReadXml("D:\\Sample\\Items");     ...