Dependency Injection

  I think I need to know more about this topic. So I will started reading from these links below. I thought I’d take a quick look at Windsor.

Dependency Injection

Dependency injection, From Wikipedia

https://en.wikipedia.org/wiki/Dependency_injection

 

 

   

Dependency Injection - Windsor

Windsor - source code

https://gojko.net/resources/windsor-facilities-20081023.zip

Castle project main web site

https://www.castleproject.org/

Automocking container

https://blog.eleutian.com/CommentView,guid,762249da-e25a-4503-8f20-c6d59b1a69bc.aspx

Method validator facility

https://using.castleproject.org/display/Contrib/Castle.Facilities.MethodValidator

Inversion of Control and Dependency Injection: Working with Windsor Container

https://msdn.microsoft.com/en-us/library/aa973811.aspx

Inversion of Control and Dependency Injection with Castle Windsor Container - Part I

https://dotnetslackers.com/Part1.aspx

 

 

  Let’s first show “tight coupling” - Later we’ll “de-couple” our code
 // Tightly coupled. The CarService() is locked into a 
// specific engine.
ICar car = new CarService();
car.setPedalPressure(12);
float speed = car.getSpeed();
MessageBox.Show("Speed is " + speed.ToString(), "**NOTE**", MessageBoxButton.OK);
 
 
CarService – Locked in

 

  
 
  We introduce Dependency Injection to lower coupling
  Dependency Injection Implemented

bullet

The user of DefaultCarService can choose the engine implementation.

bullet

Notice the yellow highlighted text - the DefaultCarService takes two types of engines

bullet

DefaultEngine - one of the two engine types that can be injected

bullet

BigV8Engine - one of the two engine types that can be injected

Notice that the DefaultCarService constructor supports dependency injection

// Main code decides on the engine implementation. We chose Default but we // cloud choose BigV8EngineService()

ICar car = new DefaultCarService(new DefaultEngineService()); car.setPedalPressure(12); float speed = car.getSpeed(); MessageBox.Show(Speed is + speed.ToString(), **NOTE**, MessageBoxButton.OK);

// Easily swap in a completely different and highly decoupled Engine Service

car = new DefaultCarService(new BigV8EngineService()); car.setPedalPressure(12); speed = car.getSpeed(); MessageBox.Show(Speed is + speed.ToString(), **NOTE**, MessageBoxButton.OK);

  
 
 
 

class DefaultCarService : ICar { IEngine _engine = null; public DefaultCarService(IEngine engineImplementation) { _engine = engineImplementation; } public float getSpeed() { return _engine.getEngineRotation(); } public void setPedalPressure(float pedal_pressure) { if (pedal_pressure > 4.0 && pedal_pressure <= 6) _engine.setFuelConsumptionRate(23.3F); else if (pedal_pressure > 6.0) _engine.setFuelConsumptionRate(33.3F); else { _engine.setFuelConsumptionRate(13.3F); } } }