Search This Blog

Wednesday, December 24, 2014

Dependency Injection C# Example

C# > PatternsDependency Injection 

Dependency injection promotes loose coupling of components by passing dependencies to an object rather than having an object instantiate its own dependencies.(http://www.blackwasp.co.uk/DependencyInjection.aspx)

       




Example

        public interface ITruck
        {
            void Go(double distance);
        }


        public class Truck : ITruck
        {
            public double Consumption{ get; set; }
            public void Go(double distance)
            {
                double necessary_fuel = Consumption * distance;
            }
        }


        public interface IRoute
        {
            void AddTruck(ITruck dependency);
        }


        public class Route : IRoute
        {
            ITruck _truck;
            public double Distance { get; set; }

            public void AddTruck(ITruck truck)
            {
                _truck = truck;
            }

            public void TruckGo()
            {
                _truck.Go(Distance);
            }
        }


            Route route = new Route();
            route.Distance = 100;

            Truck truck = new Truck();
            truck.Consumption = 20;
           
            route.AddTruck(truck);

            route.TruckGo();