Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Dependency injection

501 views

Published on

  • Be the first to comment

  • Be the first to like this

Dependency injection

  1. 1. Dependency InjectionChester HartinCode review 10/21/11
  2. 2. Introduction What is dependency injection?  Constructor injection  Setter injection  Interface Injection  DI Caution
  3. 3. What is Dependency Injection A type of loC (Inversion of Control) where we move the creation and binding of a dependency outside of the class that depends on it
  4. 4. Packing a lunch
  5. 5. Lunch Will Be Provided
  6. 6. Where Do Dependencies Come From? MyClass IDependency Dependency
  7. 7. Where Do Dependencies Come From? InjectorMyClass IDependency Dependency
  8. 8. Constructor Injection Most Common Simple  Passdependency into dependent class via constructor
  9. 9. Examplepublic class Injector { ICreditCard creditCard = new MasterCard(); Shopper shopper = new Shopper(creditCard); }public class Shopper { private readonly ICreditCard creditCard; public Shopper(ICreditCard creditCard) { this.creditCard = creditCard; } }
  10. 10. Setter Injection Create a setter on the dependent class Use the setter to set the dependency
  11. 11. Examplepublic class Injector { ICreditCard creditCard = new MasterCard(); Shopper shopper = new Shopper(); shopper.CreditCard = creditCard; }public class Shopper { public ICreditCard CreditCard { get; set; } }
  12. 12. Interface Injection Dependent class implements an interface Injector uses the interface to set the dependency
  13. 13. Examplepublic class Injector { ICreditCard creditCard = new MasterCard(); Shopper shopper = new Shopper(); ((IDependOnCreditCard)shopper).Inject(creditCard); } public class Shopper: IDependOnCreditCard { private ICreditCard creditCard; public void Inject(ICreditCard creditCard) { this.creditCard = creditCard; } } public interface IDependOnCreditCard { void Inject(ICreditCard creditCard); }
  14. 14. DI Caution Leaks the internal implementation details of a class  Violates encapsulation  Injecting “guts” into the class Prevents deferred creation  Dependencies created before needed Numbs you from the pain  Easier to unit test classes that should be broken up  Watch out for too many dependencies
  15. 15. DI Open-Source Libraries Unity Castle Windsor Structure Maps Ninject

×