with DI
Mountain View, Sep. 25th, 2013
South Bay.NET
User Group
Cut your
Dependencies
Theo Jungeblut
• Engineering manager & lead by day
at AppDynamics in San Francisco
• Coder & software craftsman by night,
...
Rate Session & Win a Shirt
http://www.speakerrate.com/theoj
Where to get the Slides
http://www.slideshare.net/theojungeblut
Overview
• What is the issue?
• What is Dependency Injection?
• What are Dependencies?
• What is the IoC-Container doing f...
UI
Service
ProcessorProcessor
Service
ResourcesResources
UI
Processor
A cleanly layered Architecture
What is the problem?
What is Clean Code?
Clean Code is maintainable
Source code must be:
• readable & well structured
• extensible
• testable
Code Maintainability *
Principles Patterns Containers
Why? How? What?
Extensibility Clean Code Tool reuse
* from: Mark See...
What is
Dependency Injection?
Without Dependency Injection
public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new ...
public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new Logger();
this.logger.Log(“Co...
Inversion of Control –
Constructor Injectionhttp://www.martinfowler.com/articles/injection.html
public class ExampleClass
...
Why is Dependency
Injection beneficial?
Benefits of Dependency Injection
Benefit Description
Late binding Services can be swapped with
other services.
Extensibili...
The Adapter Pattern
from Gang of Four, “Design Patterns”
What
are
Dependencies ?
Stable Dependency
“A DEPENDENCY that can be referenced
without any detrimental effects.
The opposite of a VOLATILE DEPENDE...
Volatile Dependency
“A DEPENDENCY that involves side effects that
may be undesirable at times.
This may include modules th...
Lifetime
a Job
for the Container
public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new Logger();
this.logger.Log(“Co...
“Register, Resolve, Release”
“Three Calls Pattern by Krzysztof Koźmic: http://kozmic.pl/
1. Register
2. Resolve
Build
up
Y...
What the IoC-Container will do for you
1. Register
2. Resolve
Build
up
Release
Clean
up
Separation of Concern (SoC)
probably by Edsger W. Dijkstra in 1974
You code
Execu
te
• Focus on purpose of your code
• Kno...
The 3 Dimensions of DI
1.Object Composition
2.Object Lifetime
3.Interception
Register - Composition Root
• XML based Configuration
• Code based Configuration
• Convention based (Discovery)
Resolve
Resolve a single object request for
example by Constructor Injection
by resolving the needed object
graph for this...
Release
Release objects from Container
when not needed anymore.
Anti
Patterns
Control Freak
http://www.freakingnews.com/The-Puppet-Master-will-play-Pics-102728.asp
// UNITY Example
internal static class Program
{
private static UnityContainer unityContainer;
private static SingleContac...
// UNITY Example
internal static class Program
{
private static UnityContainer unityContainer;
private static SingleContac...
Inversion of Control –
Setter (Property) Injection
// UNITY Example
public class ContactManager : IContactManager
{
[Depen...
Property Injection
+ Easy to understand
- Hard to implement robust
* Take if an good default exists
- Limited in applicati...
Method Injection
public class ContactManager : IContactManager
{
….
public bool Save (IContactPersistencecontactDatabaseSe...
Method Injection
• Needed for handling changing
dependencies in method calls
Ambient Context
public class ContactManager : IContactManager
{
….
public bool Save (….)
{
….
IUser currentUser = Applicat...
Ambient Context
• Avoids polluting an API with Cross
Cutting Concerns
• Only for Cross Cutting Concerns
• Limited in appli...
Interception
Public class LoggingInterceptor : IContactManager
{
public bool Save(IContact contact)
{
bool success;
this. ...
Dependency Injection Container & more
• Typically support all types of Inversion of Control mechanisms
• Constructor Injec...
The “Must Read”-Book(s)
http://www.manning.com/seemann/
by Mark Seemann
Dependency
Injection is a set of
software design
p...
Summary Clean Code - DI
Maintainability is achieved through:
• Simplification, Specialization Decoupling
(KISS, SoC, IoC, ...
Downloads,
Feedback & Comments:
Q & A
Graphic by Nathan Sawaya courtesy of brickartist.com
theo@designitright.net
www.desi...
References…
http://www.manning.com/seemann/
http://en.wikipedia.org/wiki/Keep_it_simple_stupid
http://picocontainer.org/pa...
Blog, Rating, Slides
http://www.DesignItRight.net
www.speakerrate.com/theoj
www.slideshare.net/theojungeblut
… thanks for you attention!
And visit and support
Please fill out the
feedback, and…
www.speakerrate.com/theoj
Cut your Dependencies with - Dependency Injection for South Bay.NET User Group (09/25/2013)
Upcoming SlideShare
Loading in …5
×

Cut your Dependencies with - Dependency Injection for South Bay.NET User Group (09/25/2013)

1,977 views

Published on

Dependency injection is a design patter with the potential to write cleaner code. Over the lifetime of a product, maintaining the product is actual one - if the the most - expensive areas of the overall product costs. Writing clean code can significantly lower these costs. Writing clean code also makes you more efficient during the initial development time and results in a more stable code base.

In this talk, we will dive into the basics of Inversion of Control (IoC) and Dependency Injection (DI) to review different ways of achieving decoupling. We will explorer best practices, design, and anti-patterns.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,977
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
15
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Cut your Dependencies with - Dependency Injection for South Bay.NET User Group (09/25/2013)

  1. 1. with DI Mountain View, Sep. 25th, 2013 South Bay.NET User Group Cut your Dependencies
  2. 2. Theo Jungeblut • Engineering manager & lead by day at AppDynamics in San Francisco • Coder & software craftsman by night, house builder and soon to be dad • Architects decoupled solutions & crafts maintainable code to last • Worked in healthcare and factory automation, building mission critical applications, framework & platforms • Degree in Software Engineering and Network Communications • Enjoys cycling, running and eating theo@designitright.net www.designitright.net
  3. 3. Rate Session & Win a Shirt http://www.speakerrate.com/theoj
  4. 4. Where to get the Slides http://www.slideshare.net/theojungeblut
  5. 5. Overview • What is the issue? • What is Dependency Injection? • What are Dependencies? • What is the IoC-Container doing for you? • What, how, why? • Q & A
  6. 6. UI Service ProcessorProcessor Service ResourcesResources UI Processor A cleanly layered Architecture
  7. 7. What is the problem?
  8. 8. What is Clean Code?
  9. 9. Clean Code is maintainable Source code must be: • readable & well structured • extensible • testable
  10. 10. Code Maintainability * Principles Patterns Containers Why? How? What? Extensibility Clean Code Tool reuse * from: Mark Seemann’s “Dependency Injection in .NET” presentation Bay.NET 05/2011
  11. 11. What is Dependency Injection?
  12. 12. Without Dependency Injection public class ExampleClass { private Logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); } }
  13. 13. public class ExampleClass { private Logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); } } Without Dependency Injection
  14. 14. Inversion of Control – Constructor Injectionhttp://www.martinfowler.com/articles/injection.html public class ExampleClass { private ILogger logger; public ExampleClass(ILogger logger) { this.logger = logger; if (logger == null) { throw new ArgumentNullException(“logger”); } this.logger.Log(“Constructor call”); } }
  15. 15. Why is Dependency Injection beneficial?
  16. 16. Benefits of Dependency Injection Benefit Description Late binding Services can be swapped with other services. Extensibility Code can be extended and reused in ways not explicitly planned for. Parallel development Code can be developed in parallel. Maintainability Classes with clearly defined responsibilities are easier to maintain. TESTABILITY Classes can be unit tested. * from Mark Seemann’s “Dependency Injection in .NET”, page 16
  17. 17. The Adapter Pattern from Gang of Four, “Design Patterns”
  18. 18. What are Dependencies ?
  19. 19. Stable Dependency “A DEPENDENCY that can be referenced without any detrimental effects. The opposite of a VOLATILE DEPENDENCY. “ * From Glossary: Mark Seemann’s “Dependency Injection in .NET”
  20. 20. Volatile Dependency “A DEPENDENCY that involves side effects that may be undesirable at times. This may include modules that don’t yet exist, or that have adverse requirements on its runtime environment. These are the DEPENDENCIES that are addressed by DI.“ * From Glossary: Mark Seemann’s “Dependency Injection in .NET”
  21. 21. Lifetime a Job for the Container
  22. 22. public class ExampleClass { private Logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); } } Without Dependency Injection
  23. 23. “Register, Resolve, Release” “Three Calls Pattern by Krzysztof Koźmic: http://kozmic.pl/ 1. Register 2. Resolve Build up You code Execu te Release Clean up
  24. 24. What the IoC-Container will do for you 1. Register 2. Resolve Build up Release Clean up
  25. 25. Separation of Concern (SoC) probably by Edsger W. Dijkstra in 1974 You code Execu te • Focus on purpose of your code • Know only the contracts of the dependencies • No need to know implementations • No need to handle lifetime of the dependencies
  26. 26. The 3 Dimensions of DI 1.Object Composition 2.Object Lifetime 3.Interception
  27. 27. Register - Composition Root • XML based Configuration • Code based Configuration • Convention based (Discovery)
  28. 28. Resolve Resolve a single object request for example by Constructor Injection by resolving the needed object graph for this object.
  29. 29. Release Release objects from Container when not needed anymore.
  30. 30. Anti Patterns
  31. 31. Control Freak http://www.freakingnews.com/The-Puppet-Master-will-play-Pics-102728.asp
  32. 32. // UNITY Example internal static class Program { private static UnityContainer unityContainer; private static SingleContactManagerForm singleContactManagerForm; private static void InitializeMainForm() { singleContactManagerForm = unityContainer.Resolve<SingleContactManagerForm>(); } } Inversion of Control – Service Locator http://www.martinfowler.com/articles/injection.html
  33. 33. // UNITY Example internal static class Program { private static UnityContainer unityContainer; private static SingleContactManagerForm singleContactManagerForm; private static void InitializeMainForm() { singleContactManagerForm = unityContainer.Resolve<SingleContactManagerForm>(); } } Inversion of Control – Service Locator http://www.martinfowler.com/articles/injection.html
  34. 34. Inversion of Control – Setter (Property) Injection // UNITY Example public class ContactManager : IContactManager { [Dependency] public IContactPersistence ContactPersistence { get { return this.contactPersistence; } set { this.contactPersistence = value; } } } http://www.martinfowler.com/articles/injection.html
  35. 35. Property Injection + Easy to understand - Hard to implement robust * Take if an good default exists - Limited in application otherwise
  36. 36. Method Injection public class ContactManager : IContactManager { …. public bool Save (IContactPersistencecontactDatabaseService, IContact contact) { if (logger == null) { throw new ArgumentNullException(“logger”); } …. // Additional business logic executed before calling the save return contactDatabaseService.Save(contact); } } http://www.martinfowler.com/articles/injection.html
  37. 37. Method Injection • Needed for handling changing dependencies in method calls
  38. 38. Ambient Context public class ContactManager : IContactManager { …. public bool Save (….) { …. IUser currentUser = ApplicationContext.CurrentUser; …. } } * The Ambient Context object needs to have a default value if not assigned yet.
  39. 39. Ambient Context • Avoids polluting an API with Cross Cutting Concerns • Only for Cross Cutting Concerns • Limited in application otherwise
  40. 40. Interception Public class LoggingInterceptor : IContactManager { public bool Save(IContact contact) { bool success; this. logger.Log(“Starting saving’); success = this.contactManager.Save(contact); this. logger.Log(“Starting saving’); return success; } } Public class ContactManager : IContactManager { public bool Save(IContact contact) { …. return Result } } * Note: strong simplification of what logically happens through interception.
  41. 41. Dependency Injection Container & more • Typically support all types of Inversion of Control mechanisms • Constructor Injection • Property (Setter) Injection • Method (Interface) Injection • Service Locator •.NET based DI-Container • Unity • Castle Windsor • StructureMap • Spring.NET • Autofac • Puzzle.Nfactory • Ninject • PicoContainer.NET • and more Related Technology: • Managed Extensibility Framework (MEF)
  42. 42. The “Must Read”-Book(s) http://www.manning.com/seemann/ by Mark Seemann Dependency Injection is a set of software design principles and patterns that enable us to develop loosely coupled code.
  43. 43. Summary Clean Code - DI Maintainability is achieved through: • Simplification, Specialization Decoupling (KISS, SoC, IoC, DI) • Dependency Injection Constructor Injection as default, Property and Method Injection as needed, Ambient Context for Dependencies with a default, Service Locator never • Registration Configuration by Convention if possible, exception in Code as needed Configuration by XML for explicit extensibility and post compile setup • Quality through Testability (all of them!) Graphic by Nathan Sawaya courtesy of brickartist.com
  44. 44. Downloads, Feedback & Comments: Q & A Graphic by Nathan Sawaya courtesy of brickartist.com theo@designitright.net www.designitright.net www.speakerrate.com/theoj
  45. 45. References… http://www.manning.com/seemann/ http://en.wikipedia.org/wiki/Keep_it_simple_stupid http://picocontainer.org/patterns.html http://en.wikipedia.org/wiki/Dependency_inversion_principle http://en.wikipedia.org/wiki/Don't_repeat_yourself http://en.wikipedia.org/wiki/Component-oriented_programming http://en.wikipedia.org/wiki/Service-oriented_architecture http://www.martinfowler.com/articles/injection.html http://www.codeproject.com/KB/aspnet/IOCDI.aspx http://msdn.microsoft.com/en-us/magazine/cc163739.aspx http://msdn.microsoft.com/en-us/library/ff650320.aspx http://msdn.microsoft.com/en-us/library/aa973811.aspx http://msdn.microsoft.com/en-us/library/ff647976.aspx http://msdn.microsoft.com/en-us/library/cc707845.aspx http://msdn.microsoft.com/en-us/library/bb833022.aspx http://unity.codeplex.com/ Lego (trademarked in capitals as LEGO)
  46. 46. Blog, Rating, Slides http://www.DesignItRight.net www.speakerrate.com/theoj www.slideshare.net/theojungeblut
  47. 47. … thanks for you attention! And visit and support Please fill out the feedback, and… www.speakerrate.com/theoj

×