SlideShare une entreprise Scribd logo
1  sur  69
Dependency Injection with Unity 2.0 DmytroMindra RnD Tech Lead Lohika Вторая встреча Microsoft .Net User Group Одесса, 2010
Goal Get DI understanding Get Unity 2.0 understanding Learn how to add Unity 2.0 to your projects
Plan Inversion of Control principle (IoC) Dependency Injection pattern (DI) Unity 2.0 Live Demo
Problem
Problem We live in an age where writing software to a given set of requirements is no longer enough. We have to maintain and change existing code.
How? Our solutions should be: Modular Testable Adaptive to change
Terms Service —An object that performs a well-defined function when called upon Client—Any consumer of a service; an object that calls upon a service to perform a well-understood function
Terms Dependency —A specific service that is required by another object to fulfill its function. Dependent—A client object that needs a dependency (or dependencies) in order to perform its function.
PRE DI APPROACHES
Ex1:Composition
Ex1:Composition public class SpellCheckerService{} public class TextEditor     { private SpellCheckerService _spellCheckerService; public TextEditor()         {             _spellCheckerService = new SpellCheckerService();            }     } class Program     { static void Main(string[] args)         { TextEditor textEditor = new TextEditor();         }     }
What’s good It’s simple
What’s bad It’s not testable It’s hard to maintain/change
Ex2: Factory
Ex2: Factory  public interface ISpellCheckerService     { string CheckSpelling();     }
Ex2: Factory 	public class SpellCheckerService: ISpellCheckerService     { public string CheckSpelling()         {             return “Real”;         }     }
Ex2: Factory public class SpellCheckerFactory     { private static ISpellCheckerService _spellCheckerService = new SpellCheckerService(); 	     public static ISpellCheckerServiceSpellCheckerService         { get{ return _spellCheckerService;  }             set{ _spellCheckerService = value; }         }     }
Ex2: Factory public class TextEditor { private ISpellCheckerService _spellCheckerService; public TextEditor()         {             _spellCheckerService = SpellCheckerFactory.SpellCheckerService;         } public string CheckSpelling()         {             return _spellCheckerService.CheckSpelling();         } }
Ex2:Factory Unit Testing 	public class SpellCheckerServiceMock: ISpellCheckerService     { public string CheckSpelling()         {             return “Mock”;         } }
Ex2:Factory Unit Testing [TestFixture] class EmailerFactoryUnitTests     {         [Test] public void EmailerFactoryTest()         { ISpellCheckerServicemockSpellCheckerService = new SpellCheckerServiceMock(); SpellCheckerFactory.SpellCheckerService = mockSpellCheckerService; TextEditortextEditor = new TextEditor(); Assert.AreEqual(“Mock”, textEditor.CheckSpelling());         }     }
Ex2: Factory
What changed TextEditor is still looking for its dependencies by itself. But now we can plug in different services without letting him know.
What’s good It’s testable It’s easier to maintain/change
What’s bad You have to maintain factory or service locator Dependent is still looking for Dependencies by himself. Dependencies are encapsulated and are not obvious.
Service Locator Unfortunately, being a kind of Factory, Service Locators suffer from the same problems of testability and shared state.
Inversion of Control Common Flow TextEditor creates its dependency by himself. IoC Flow TextEditor requests factory to create dependency for him.
Inversion of Control Hollywood Principle:  Don’t call me, I’ll call you
Inversion of Control IoC –  is a common characteristic of frameworks. Inversion of Control serves as a design guideline. According to Martin Fowler the etymology  of the phrase dates back to 1988.
Two principles of IOC Main classes aggregating other classes should not depend on the direct implementation of the aggregated classes. Both the classes should depend on abstraction.  Abstraction should not depend on details, details should depend on abstraction.
Inversion of Controlas a Design Guideline Without IoC With IoC Loose coupling
Time TO INJECT !
Ex3:Dependency Injection public class TextEditor     { private readonlyISpellCheckerService _spellCheckerService; public TextEditor(ISpellCheckerServicespellCheckerService)         {             _spellCheckerService = spellCheckerService;         } public string CheckSpelling()         {             return _spellCheckerService.CheckSpelling();         } }
Ex3: Unit Testing DI Almost same as for Ex2 // Mock  ISpellCheckerService mock = new SpellCheckerServiceMock(); // Instantiate TextEditortextEditor = new TextEditor(mock); // Check Assert.AreEqual(“Mock”, textEditor.CheckSpelling());
What changed TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself.
What’s good Dependencies are obvious. Dependency resolution is not encapsulated. Unit Testing got little bit easier Architecture is much better
What’s bad We are resolving dependencies manually while creating instances of TextEditor.
Dependency Injection
Dependency Injection DI is IoC Inversion of Control is too generic a term DI pattern – describes the approach used to lookup a dependency.  Dependency resolution is moved to Framework.
Ex4: Unity
Ex4: Unity using Microsoft.Practices.Unity; UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); TextEditortextEditor = container.Resolve<TextEditor>();
What changed Unity container now resolves dependencies
What’s good Automated dependency resolution
Unity methods RegisterType RegisterInstance Resolve BuildUp
Ex5: Unity Configuration 	  <configSections>   <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>  </configSections>  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">    <alias alias="ISpellCheckerService" type="Unity.Config.ISpellCheckerService, Unity.Config" />    <alias alias="SpellCheckingService" type="Unity.Config.SpellCheckingService, Unity.Config" />    <namespace name="Unity.Config" />    <assembly name="Unity.Config" />    <container>      <register type="ISpellCheckerService" mapTo="SpellCheckingService" />    </container>  </unity>
Ex5: Unity Configuration 	using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;UnityContainer container = new UnityContainer();container.LoadConfiguration();TextEditor textEditor = container.Resolve<TextEditor>();
Dependency tree
Ex6: Dependency tree public interface IAdditionalDependency{} public class AdditionalDependency : IAdditionalDependency{} public class SpellCheckingService: ISpellCheckerService  {        public SpellCheckingService( IAdditionalDependency dependency){}   }
Ex6: Dependency Tree UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>();container.RegisterType<IAdditionalDependency,  AdditionalDependency>();TextEditor textEditor = container.Resolve<TextEditor>();
Ex6: Dependency tree
Injection Types Constructor Injection Setter injection Method call injection
Ex7: Defining Injection Constructor     public class TextEditor    {        private readonly ISpellCheckerService _spellCheckerService;        [InjectionConstructor]                public TextEditor(ISpellCheckerService spellCheckerService)        {            _spellCheckerService = spellCheckerService;        }        public TextEditor(ISpellCheckerService spellCheckerService,string name)        {            _spellCheckerService = spellCheckerService;        }    }
Ex8: Property Injection     public class TextEditor    {        public ISpellCheckerService SpellCheckerService {get; set;}        [Dependency]        public ISpellCheckerService YetAnotherSpellcheckerService{get;set;}    }             UnityContainer container = new UnityContainer();            container.RegisterType<TextEditor>(new InjectionProperty("SpellCheckerService"));            container.RegisterType<ISpellCheckerService, SpellCheckingService>();            TextEditor textEditor = container.Resolve<TextEditor>();
Ex9: Method call injection     public class TextEditor    {        public ISpellCheckerService SpellcheckerService {get; set;}         [InjectionMethod]        public void Initialize (ISpellCheckerService spellcheckerService)        {            _spellCheckerService = spellcheckerService;        }     } UnityContainer container = new UnityContainer();//container.RegisterType<TextEditor>( new InjectionMethod("SpellcheckerService"));container.RegisterType<ISpellCheckerService, SpellCheckingService>();TextEditor textEditor = container.Resolve<TextEditor>();
Lifetime Managers TransientLifetimeManagerReturns a new instance of the requested type for each call. (default behavior) ContainerControlledLifetimeManagerImplements a singleton behavior for objects. The object is disposed of when you dispose of the container.
Lifetime Managers ExternallyControlledLifetimeManagerImplements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope.  HierarchicalifetimeManagerImplements a singleton behavior for objects. However, child containers don't share instances with parents.
Lifetime Managers PerResolveLifetimeManagerImplements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph.  PerThreadLifetimeManagerImplements a singleton behavior for objects but limited to the current thread.
Ex10: Unity Singleton UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>(new ContainerControlledLifetimeManager());TextEditor textEditor = container.Resolve<TextEditor>();
Container Hierarchy
Unity Limitations ,[object Object]
When your dependencies are very simple and do not require abstraction. ,[object Object]
Performance
Performance
Performance
.NET DI Frameworks Unity 2.0 AutoFac 2.3.2 StructureMap 2.6.1 Castle Windsor 2.1 Ninject 2.0
Additional reading
Additional reading
Live Demo
Questions ?
Thank YOU !

Contenu connexe

Tendances

Tendances (19)

Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
JMockit
JMockitJMockit
JMockit
 
Analyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyAnalyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics Company
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Testing And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionTesting And Mxunit In ColdFusion
Testing And Mxunit In ColdFusion
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-exam
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit Tests
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
3 j unit
3 j unit3 j unit
3 j unit
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 

En vedette (9)

Mike ponomarenko java17-fork-v1.2
Mike ponomarenko java17-fork-v1.2Mike ponomarenko java17-fork-v1.2
Mike ponomarenko java17-fork-v1.2
 
Sql server clr integration
Sql server clr integration Sql server clr integration
Sql server clr integration
 
Overview of PaaS: Java experience
Overview of PaaS: Java experienceOverview of PaaS: Java experience
Overview of PaaS: Java experience
 
Enterprise or not to enterprise
Enterprise or not to enterpriseEnterprise or not to enterprise
Enterprise or not to enterprise
 
Silverlight 4, есть ли жизнь на десктопе
Silverlight 4, есть ли жизнь на десктопеSilverlight 4, есть ли жизнь на десктопе
Silverlight 4, есть ли жизнь на десктопе
 
Test driven development in net
Test driven development in netTest driven development in net
Test driven development in net
 
New features of Windows Phone 7.5
New features of Windows Phone 7.5New features of Windows Phone 7.5
New features of Windows Phone 7.5
 
Разработка расширений Firefox
Разработка расширений FirefoxРазработка расширений Firefox
Разработка расширений Firefox
 
JSF2
JSF2JSF2
JSF2
 

Similaire à Dependency injection with unity 2.0 Dmytro Mindra Lohika

Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz lin
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Clean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code CampClean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code Camp
Theo Jungeblut
 

Similaire à Dependency injection with unity 2.0 Dmytro Mindra Lohika (20)

IOC in Unity
IOC in Unity  IOC in Unity
IOC in Unity
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class Design
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Swiz DAO
Swiz DAOSwiz DAO
Swiz DAO
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Oleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
Oleksandr Valetskyy - Become a .NET dependency injection ninja with NinjectOleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
Oleksandr Valetskyy - Become a .NET dependency injection ninja with Ninject
 
A logic foundation for template-based program transformation in Eclipse
A logic foundation for template-based program transformation in EclipseA logic foundation for template-based program transformation in Eclipse
A logic foundation for template-based program transformation in Eclipse
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Command pattern in java
Command pattern in javaCommand pattern in java
Command pattern in java
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mocking
 
Clean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code CampClean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code Camp
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
 
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
 

Plus de Alex Tumanoff

Navigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoNavigation map factory by Alexey Klimenko
Navigation map factory by Alexey Klimenko
Alex Tumanoff
 
Serialization and performance by Sergey Morenets
Serialization and performance by Sergey MorenetsSerialization and performance by Sergey Morenets
Serialization and performance by Sergey Morenets
Alex Tumanoff
 
Async clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAsync clinic by by Sergey Teplyakov
Async clinic by by Sergey Teplyakov
Alex Tumanoff
 
Deep Dive C# by Sergey Teplyakov
Deep Dive  C# by Sergey TeplyakovDeep Dive  C# by Sergey Teplyakov
Deep Dive C# by Sergey Teplyakov
Alex Tumanoff
 
Bdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergBdd by Dmitri Aizenberg
Bdd by Dmitri Aizenberg
Alex Tumanoff
 

Plus de Alex Tumanoff (20)

Sql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen NedaskivskyiSql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen Nedaskivskyi
 
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis ReznikOdessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
 
Azure data bricks by Eugene Polonichko
Azure data bricks by Eugene PolonichkoAzure data bricks by Eugene Polonichko
Azure data bricks by Eugene Polonichko
 
Sdlc by Anatoliy Anthony Cox
Sdlc by  Anatoliy Anthony CoxSdlc by  Anatoliy Anthony Cox
Sdlc by Anatoliy Anthony Cox
 
Kostenko ux november-2014_1
Kostenko ux november-2014_1Kostenko ux november-2014_1
Kostenko ux november-2014_1
 
Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3
 
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас..."Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
 
Spring.new hope.1.3
Spring.new hope.1.3Spring.new hope.1.3
Spring.new hope.1.3
 
Sql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton VidishchevSql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton Vidishchev
 
Navigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoNavigation map factory by Alexey Klimenko
Navigation map factory by Alexey Klimenko
 
Serialization and performance by Sergey Morenets
Serialization and performance by Sergey MorenetsSerialization and performance by Sergey Morenets
Serialization and performance by Sergey Morenets
 
Игры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей РыбаковИгры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей Рыбаков
 
Android sync adapter
Android sync adapterAndroid sync adapter
Android sync adapter
 
Async clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAsync clinic by by Sergey Teplyakov
Async clinic by by Sergey Teplyakov
 
Deep Dive C# by Sergey Teplyakov
Deep Dive  C# by Sergey TeplyakovDeep Dive  C# by Sergey Teplyakov
Deep Dive C# by Sergey Teplyakov
 
Bdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergBdd by Dmitri Aizenberg
Bdd by Dmitri Aizenberg
 
Неформальные размышления о сертификации в IT
Неформальные размышления о сертификации в ITНеформальные размышления о сертификации в IT
Неформальные размышления о сертификации в IT
 
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So..."AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
 
Patterns of parallel programming
Patterns of parallel programmingPatterns of parallel programming
Patterns of parallel programming
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
 

Dependency injection with unity 2.0 Dmytro Mindra Lohika

  • 1. Dependency Injection with Unity 2.0 DmytroMindra RnD Tech Lead Lohika Вторая встреча Microsoft .Net User Group Одесса, 2010
  • 2. Goal Get DI understanding Get Unity 2.0 understanding Learn how to add Unity 2.0 to your projects
  • 3. Plan Inversion of Control principle (IoC) Dependency Injection pattern (DI) Unity 2.0 Live Demo
  • 5. Problem We live in an age where writing software to a given set of requirements is no longer enough. We have to maintain and change existing code.
  • 6. How? Our solutions should be: Modular Testable Adaptive to change
  • 7. Terms Service —An object that performs a well-defined function when called upon Client—Any consumer of a service; an object that calls upon a service to perform a well-understood function
  • 8. Terms Dependency —A specific service that is required by another object to fulfill its function. Dependent—A client object that needs a dependency (or dependencies) in order to perform its function.
  • 11. Ex1:Composition public class SpellCheckerService{} public class TextEditor { private SpellCheckerService _spellCheckerService; public TextEditor() { _spellCheckerService = new SpellCheckerService(); } } class Program { static void Main(string[] args) { TextEditor textEditor = new TextEditor(); } }
  • 13. What’s bad It’s not testable It’s hard to maintain/change
  • 15. Ex2: Factory public interface ISpellCheckerService { string CheckSpelling(); }
  • 16. Ex2: Factory public class SpellCheckerService: ISpellCheckerService { public string CheckSpelling() { return “Real”; } }
  • 17. Ex2: Factory public class SpellCheckerFactory { private static ISpellCheckerService _spellCheckerService = new SpellCheckerService(); public static ISpellCheckerServiceSpellCheckerService { get{ return _spellCheckerService; } set{ _spellCheckerService = value; } } }
  • 18. Ex2: Factory public class TextEditor { private ISpellCheckerService _spellCheckerService; public TextEditor() { _spellCheckerService = SpellCheckerFactory.SpellCheckerService; } public string CheckSpelling() { return _spellCheckerService.CheckSpelling(); } }
  • 19. Ex2:Factory Unit Testing public class SpellCheckerServiceMock: ISpellCheckerService { public string CheckSpelling() { return “Mock”; } }
  • 20. Ex2:Factory Unit Testing [TestFixture] class EmailerFactoryUnitTests { [Test] public void EmailerFactoryTest() { ISpellCheckerServicemockSpellCheckerService = new SpellCheckerServiceMock(); SpellCheckerFactory.SpellCheckerService = mockSpellCheckerService; TextEditortextEditor = new TextEditor(); Assert.AreEqual(“Mock”, textEditor.CheckSpelling()); } }
  • 22. What changed TextEditor is still looking for its dependencies by itself. But now we can plug in different services without letting him know.
  • 23. What’s good It’s testable It’s easier to maintain/change
  • 24. What’s bad You have to maintain factory or service locator Dependent is still looking for Dependencies by himself. Dependencies are encapsulated and are not obvious.
  • 25. Service Locator Unfortunately, being a kind of Factory, Service Locators suffer from the same problems of testability and shared state.
  • 26. Inversion of Control Common Flow TextEditor creates its dependency by himself. IoC Flow TextEditor requests factory to create dependency for him.
  • 27. Inversion of Control Hollywood Principle: Don’t call me, I’ll call you
  • 28. Inversion of Control IoC –  is a common characteristic of frameworks. Inversion of Control serves as a design guideline. According to Martin Fowler the etymology of the phrase dates back to 1988.
  • 29. Two principles of IOC Main classes aggregating other classes should not depend on the direct implementation of the aggregated classes. Both the classes should depend on abstraction. Abstraction should not depend on details, details should depend on abstraction.
  • 30. Inversion of Controlas a Design Guideline Without IoC With IoC Loose coupling
  • 32. Ex3:Dependency Injection public class TextEditor { private readonlyISpellCheckerService _spellCheckerService; public TextEditor(ISpellCheckerServicespellCheckerService) { _spellCheckerService = spellCheckerService; } public string CheckSpelling() { return _spellCheckerService.CheckSpelling(); } }
  • 33. Ex3: Unit Testing DI Almost same as for Ex2 // Mock ISpellCheckerService mock = new SpellCheckerServiceMock(); // Instantiate TextEditortextEditor = new TextEditor(mock); // Check Assert.AreEqual(“Mock”, textEditor.CheckSpelling());
  • 34. What changed TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself.
  • 35. What’s good Dependencies are obvious. Dependency resolution is not encapsulated. Unit Testing got little bit easier Architecture is much better
  • 36. What’s bad We are resolving dependencies manually while creating instances of TextEditor.
  • 38. Dependency Injection DI is IoC Inversion of Control is too generic a term DI pattern – describes the approach used to lookup a dependency. Dependency resolution is moved to Framework.
  • 40. Ex4: Unity using Microsoft.Practices.Unity; UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); TextEditortextEditor = container.Resolve<TextEditor>();
  • 41. What changed Unity container now resolves dependencies
  • 42. What’s good Automated dependency resolution
  • 43. Unity methods RegisterType RegisterInstance Resolve BuildUp
  • 44. Ex5: Unity Configuration   <configSections>   <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>  </configSections>  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">    <alias alias="ISpellCheckerService" type="Unity.Config.ISpellCheckerService, Unity.Config" />    <alias alias="SpellCheckingService" type="Unity.Config.SpellCheckingService, Unity.Config" />    <namespace name="Unity.Config" />    <assembly name="Unity.Config" />    <container>      <register type="ISpellCheckerService" mapTo="SpellCheckingService" />    </container>  </unity>
  • 45. Ex5: Unity Configuration using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;UnityContainer container = new UnityContainer();container.LoadConfiguration();TextEditor textEditor = container.Resolve<TextEditor>();
  • 47. Ex6: Dependency tree public interface IAdditionalDependency{} public class AdditionalDependency : IAdditionalDependency{} public class SpellCheckingService: ISpellCheckerService  {        public SpellCheckingService( IAdditionalDependency dependency){}   }
  • 48. Ex6: Dependency Tree UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>();container.RegisterType<IAdditionalDependency,  AdditionalDependency>();TextEditor textEditor = container.Resolve<TextEditor>();
  • 50. Injection Types Constructor Injection Setter injection Method call injection
  • 51. Ex7: Defining Injection Constructor     public class TextEditor    {        private readonly ISpellCheckerService _spellCheckerService;        [InjectionConstructor]                public TextEditor(ISpellCheckerService spellCheckerService)        {            _spellCheckerService = spellCheckerService;        }        public TextEditor(ISpellCheckerService spellCheckerService,string name)        {            _spellCheckerService = spellCheckerService;        }    }
  • 52. Ex8: Property Injection     public class TextEditor    {        public ISpellCheckerService SpellCheckerService {get; set;}        [Dependency]        public ISpellCheckerService YetAnotherSpellcheckerService{get;set;}    }             UnityContainer container = new UnityContainer();            container.RegisterType<TextEditor>(new InjectionProperty("SpellCheckerService"));            container.RegisterType<ISpellCheckerService, SpellCheckingService>();            TextEditor textEditor = container.Resolve<TextEditor>();
  • 53. Ex9: Method call injection     public class TextEditor    {        public ISpellCheckerService SpellcheckerService {get; set;}         [InjectionMethod]        public void Initialize (ISpellCheckerService spellcheckerService)        {            _spellCheckerService = spellcheckerService;        }     } UnityContainer container = new UnityContainer();//container.RegisterType<TextEditor>( new InjectionMethod("SpellcheckerService"));container.RegisterType<ISpellCheckerService, SpellCheckingService>();TextEditor textEditor = container.Resolve<TextEditor>();
  • 54. Lifetime Managers TransientLifetimeManagerReturns a new instance of the requested type for each call. (default behavior) ContainerControlledLifetimeManagerImplements a singleton behavior for objects. The object is disposed of when you dispose of the container.
  • 55. Lifetime Managers ExternallyControlledLifetimeManagerImplements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope. HierarchicalifetimeManagerImplements a singleton behavior for objects. However, child containers don't share instances with parents.
  • 56. Lifetime Managers PerResolveLifetimeManagerImplements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph. PerThreadLifetimeManagerImplements a singleton behavior for objects but limited to the current thread.
  • 57. Ex10: Unity Singleton UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>(new ContainerControlledLifetimeManager());TextEditor textEditor = container.Resolve<TextEditor>();
  • 59.
  • 60.
  • 64. .NET DI Frameworks Unity 2.0 AutoFac 2.3.2 StructureMap 2.6.1 Castle Windsor 2.1 Ninject 2.0