Monday, November 27, 2017

Why and How to implement Dependency Injection Pattern?

Benefits

By using dependency injection, you solve two main problems,

1- Unit Test
2- Instantiation

Unit Test

You can resolve this by implementing interface of every class that is required to instantiated in any method or implementation. Always pass interface as parameter in constructor rather than making variables and instantiate in the class. For unit test, you can send mocked (the dummy) instantiation of that interface to that class.

Before

        public class Order
        {
            public string ID { get; set; }
            public string Detail { get; set; }

            public void Process()
            {
            }
        }
        public class Cart
        {
            public void ProcessOrder()
            {
                Order order = new Order();
                order.Process();
            }
        }