SlideShare a Scribd company logo
1 of 51
Download to read offline
IoC in Microsoft Unity
Francesco Garavaglia
03/2016
Agenda
 The Problem
 Composition by Examples
 Inversion of Control (IoC)
 Dependency Injection Microsoft
Unity
2
What problems
are we trying to
solve?
3
4
The 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.
 Code quality ( What’s Bad ) R.Martin 1996
- Rigid (hard to modify)
- Fragile ( errors occur on almost every change)
- Immobile (not reusable)
The Problem
How?
Our solutions should be:
• Modular
• Testable
• Adaptive to change
• Whatever you want
5
How?
Our solutions should be:
• Modular
• Testable
• Adaptive to change
• Whatever you want
6
7
We need a glossary
 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
 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.
The Problem
Composition:
OLD SCHOOL
8
9
Ex1:Composition
Composition by Examples
10
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();
}
}
TextEditor
SpellChecker
Composition by Examples
11
Ex1: Composition
•Simple
What is
Good
•It’s not testable
•It’s hard to
maintain/change
What is
Bad
Composition by Examples
Composition:
NEW SCHOOL
12
13
Better approach
TextEditor
+ CheckSpelling() : bool
SpellCheckerService
+ CheckSpelling() : string
«interface»
ISpellCheckerService
+ CheckSpelling() : string
Dependency Inversion
A.High-level modules should not
depend on low-level modules. Both
should depend on abstractions.
B. Abstractions should not depend
upon details. Details should depend
upon abstractions.
Robert C. Martin 1996
Composition by Examples
14
Context
Granny
+ Eat() : void
«interface»
IAppleProvider
+ GetApple() : IApple
RedAppleProvider
+ GetApple() : IApple
GoldenAppleProvider
+ GetApple() : IApple
«interface»
IPillProvider
ConcretePillProvider
Context
Composition by Examples
15
Ex2:Loose Coupling
public class TextEditor
{
private readonly ISpellCheckerService _spellCheckerService;
public TextEditor(ISpellCheckerService spellCheckerService)
{
_spellCheckerService = spellCheckerService;
}
public string CheckSpelling()
{
return _spellCheckerService.CheckSpelling();
}
}
Composition by Examples
16
Ex2: Unit Testing
// Mock
ISpellCheckerService mock = new SpellCheckerServiceMock();
// Instantiate
TextEditor textEditor = new TextEditor(mock);
// Check
Assert.AreEqual(“Mock”, textEditor.CheckSpelling());
Composition by Examples
17
Ex2: Good vs Bad
• Dependencies are obvious.
• Dependency resolution is not
encapsulated.
• Unit Testing is applicable
• Architecture is much better
What is
Good
• We are resolving dependencies
manually while creating instances of
TextEditor.
What is
Bad
 TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself.
Composition by Examples
18
Ex3: Using Factory
Composition by Examples
19
20
21
22
23
24
25
Factory
TextEditorFactory
+ GetEnglishTextEditor() : TextEditor
+ GetFrenchTextEditor() : TextEditor
TextEditor
FrenchSpellCheckerServ ice
«interface»
ISpellCheckerServ ice
EnglishSpellCheckerServ ice
Composition by Examples
26
What changed
 Any required combination of Text Editor and Spell Checking Service is created by object factory.
•It’s testable
•No manual wiring
What is
Good
•You have to maintain factory or service locator
•The more combinations the more methods we have in
factory.
•Your code knows about the specific factory or factory
interface. This means that infrastructure logic is mixed
with business logic.
•Factory may have states.
What is
Bad
Composition by Examples
27
Ex4: Service Locator
Unfortunately, being a kind of Factory, Service Locators suffer from the same problems
of testability and shared state.
Composition by Examples
28
What are we looking for?
Composition by Examples
Inversion of
Control
HOLLYWOOD PRINCIPLE:
DON’T CALL
ME, I’LL CALL
YOU
29
30
Inversion of Control
IoC – is a common characteristic of
frameworks.
According to Martin Fowler the etymology of
the phrase dates back to 1988.
Inversion of Control
31
Dependency Injection
 DI is a kind of 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.
Inversion of Control
32
SpellCheckerService
+ CheckSpelling() : bool
TextEditor
+ CheckSpelling() : bool
«interface»
ISpellCheckerService
We have already prepared basis
Loosely
coupled
structure
Inversion of Control
It’s time to
introduce new
role: Injector
Injector
(sometimes referred to as
a provider or container)
33
Unity
34
35
Ex5: Unity
using Microsoft.Practices.Unity;
UnityContainer container = new UnityContainer();
container.RegisterType<ISpellCheckerService, SpellCheckingService>();
TextEditor textEditor = container.Resolve<TextEditor>();
DI with Unity
36
What changed
 Unity container now resolves dependencies
•Automated dependency
resolution
•Business logic and
infrastructure are decoupled.
What is
Good
What is
Bad
DI with Unity
37
Injection Types
 Interface injection (by Martin Fowler)
 Constructor Injection (by Martin Fowler)
 Setter injection (by Martin Fowler)
 Method call injection (Unity)
 Method decorator injection (Guice)
DI with Unity
38
Unity Configuration
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Pr
actices.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>
DI with Unity
39
Unity Configuration
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
UnityContainer container = new UnityContainer();
container.LoadConfiguration();
TextEditor textEditor = container.Resolve<TextEditor>();
DI with Unity
40
Dependency tree
DI with Unity
41
Dependency tree
public interface IAdditionalDependency{}
public class AdditionalDependency : IAdditionalDependency{}
public class SpellCheckingService: ISpellCheckerService {
public SpellCheckingService( IAdditionalDependency dependency){}
}
UnityContainer container = new UnityContainer();
container.RegisterType<ISpellCheckerService, SpellCheckingService>();
container.RegisterType<IAdditionalDependency, AdditionalDependency>();
TextEditor textEditor = container.Resolve<TextEditor>();
DI with Unity
42
Dependency tree
SpellCheckerService
+ CheckSpelling() : bool
TextEditor
+ CheckSpelling() : bool
«interface»
ISpellCheckerService
AdditionalDependency
+ CheckSpelling() : bool
«interface»
IAditionalDependenct
DI with Unity
43
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;
}
}
DI with Unity
44
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>();
DI with Unity
45
Method call injection
public class TextEditor
{
public ISpellCheckerService SpellcheckerService {get; set;}
public void Initialize (ISpellCheckerService spellcheckerService)
{
_spellCheckerService = spellcheckerService;
}
}
UnityContainer container = new UnityContainer();
container.RegisterType<ISpellCheckerService, SpellCheckingService>();
TextEditor textEditor = container.Resolve<TextEditor>();
DI with Unity
46
Lifetime Managers
 TransientLifetimeManager
Returns a new instance of the requested type for each call. (default behavior)
 ContainerControlledLifetimeManager
Implements a singleton behavior for objects. The object is disposed of when you dispose of the
container.
 ExternallyControlledLifetimeManager
Implements a singleton behavior but the container doesn't hold a reference to object which will
be disposed of when out of scope.
 HierarchicalifetimeManager
Implements a singleton behavior for objects. However, child containers don't share instances
with parents.
 PerResolveLifetimeManager
Implements a behavior similar to the transient lifetime manager except that instances are reused
across build-ups of the object graph.
 PerThreadLifetimeManager
Implements a singleton behavior for objects but limited to the current thread.
DI with Unity
47
Unity Singleton
UnityContainer container = new UnityContainer();
container.RegisterType<ISpellCheckerService, SpellCheckingService>(new
ContainerControlledLifetimeManager());
TextEditor textEditor = container.Resolve<TextEditor>();
DI with Unity
48
Container Hierarchy
DI with Unity
49
Unity Limitations
• When your objects and classes have no dependencies on other objects or classes.
• When your dependencies are very simple and do not require abstraction.
DI with Unity
50
References
 Martin Fowler – Dependency Injection
http://martinfowler.com/articles/injection.html
 R. Martin - Dependency Inversion principle
http://www.objectmentor.com/resources/articles/dip.pdf
 Developer's Guide to Dependency Injection Using Unity
https://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx
Thanks
FRANCESCO.GARAVAGLIA@GMAIL.COM

More Related Content

What's hot

Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guideFahad Shiekh
 
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 CompanyPVS-Studio
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
Dependency Injection in Episerver and .Net
Dependency Injection in Episerver and .NetDependency Injection in Episerver and .Net
Dependency Injection in Episerver and .NetValdis Iljuconoks
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
SAP Testing Training
SAP Testing TrainingSAP Testing Training
SAP Testing TrainingVGlobal Govi
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testMasanori Kato
 
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 DesignJames Phillips
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practicesMarian Wamsiedel
 

What's hot (19)

Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
Deployment
DeploymentDeployment
Deployment
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guide
 
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
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
JMockit
JMockitJMockit
JMockit
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
Dependency Injection in Episerver and .Net
Dependency Injection in Episerver and .NetDependency Injection in Episerver and .Net
Dependency Injection in Episerver and .Net
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
SAP Testing Training
SAP Testing TrainingSAP Testing Training
SAP Testing Training
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_test
 
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
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Write testable code in java, best practices
Write testable code in java, best practicesWrite testable code in java, best practices
Write testable code in java, best practices
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 

Viewers also liked

Workshop - cqrs brief introduction
Workshop - cqrs brief introductionWorkshop - cqrs brief introduction
Workshop - cqrs brief introductionFrancesco Garavaglia
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETRemik Koczapski
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoMicrosoft Mobile Developer
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversionchhabraravish23
 
Spring: usarlo conviene, ma usalo bene!
Spring: usarlo conviene, ma usalo bene!Spring: usarlo conviene, ma usalo bene!
Spring: usarlo conviene, ma usalo bene!benfante
 
Inversion of Control @ CD2008
Inversion of Control @ CD2008Inversion of Control @ CD2008
Inversion of Control @ CD2008Mauro Servienti
 
Linkedin 2013 Facts & Statistics
Linkedin 2013 Facts & StatisticsLinkedin 2013 Facts & Statistics
Linkedin 2013 Facts & StatisticsMairead O'Sullivan
 
The Resonating Career
The Resonating CareerThe Resonating Career
The Resonating CareerDonald Cheng
 
Swiss Re - Analysts meeting 2002
Swiss Re - Analysts meeting 2002Swiss Re - Analysts meeting 2002
Swiss Re - Analysts meeting 2002Felix Schlumpf
 
операційні системи
операційні системиопераційні системи
операційні системиZakharchuk001
 
EU Citizens’ Rights – The way forward
EU Citizens’ Rights – The way forwardEU Citizens’ Rights – The way forward
EU Citizens’ Rights – The way forwardJoão Salgueiro Mouta
 
Monitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura itMonitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura itStefano Arduini
 
SEB BULETIN INFORMATIV OCT-NOV 2014
SEB BULETIN INFORMATIV OCT-NOV 2014SEB BULETIN INFORMATIV OCT-NOV 2014
SEB BULETIN INFORMATIV OCT-NOV 2014dan cimpean
 
MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...
MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...
MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...Russell Pierce
 
Lutilizzoditwitterinitalianel2012 121214070608-phpapp01
Lutilizzoditwitterinitalianel2012 121214070608-phpapp01Lutilizzoditwitterinitalianel2012 121214070608-phpapp01
Lutilizzoditwitterinitalianel2012 121214070608-phpapp01Eleonora Busico
 
Rakesh-Nune-Incident-Management-for-DDOT
Rakesh-Nune-Incident-Management-for-DDOTRakesh-Nune-Incident-Management-for-DDOT
Rakesh-Nune-Incident-Management-for-DDOTRakesh Nune
 

Viewers also liked (20)

Workshop - cqrs brief introduction
Workshop - cqrs brief introductionWorkshop - cqrs brief introduction
Workshop - cqrs brief introduction
 
IOC in Unity
IOC in Unity  IOC in Unity
IOC in Unity
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progetto
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
Spring: usarlo conviene, ma usalo bene!
Spring: usarlo conviene, ma usalo bene!Spring: usarlo conviene, ma usalo bene!
Spring: usarlo conviene, ma usalo bene!
 
Inversion of Control @ CD2008
Inversion of Control @ CD2008Inversion of Control @ CD2008
Inversion of Control @ CD2008
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Linkedin 2013 Facts & Statistics
Linkedin 2013 Facts & StatisticsLinkedin 2013 Facts & Statistics
Linkedin 2013 Facts & Statistics
 
The Resonating Career
The Resonating CareerThe Resonating Career
The Resonating Career
 
Sleepless nights
Sleepless nightsSleepless nights
Sleepless nights
 
Swiss Re - Analysts meeting 2002
Swiss Re - Analysts meeting 2002Swiss Re - Analysts meeting 2002
Swiss Re - Analysts meeting 2002
 
Huff slideshow
Huff slideshowHuff slideshow
Huff slideshow
 
операційні системи
операційні системиопераційні системи
операційні системи
 
EU Citizens’ Rights – The way forward
EU Citizens’ Rights – The way forwardEU Citizens’ Rights – The way forward
EU Citizens’ Rights – The way forward
 
Monitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura itMonitoraggio completo dell'infrastruttura it
Monitoraggio completo dell'infrastruttura it
 
SEB BULETIN INFORMATIV OCT-NOV 2014
SEB BULETIN INFORMATIV OCT-NOV 2014SEB BULETIN INFORMATIV OCT-NOV 2014
SEB BULETIN INFORMATIV OCT-NOV 2014
 
MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...
MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...
MA STATE HOUSE REMARKS WITH REP. CABRAL AND AUTOR JAMES BUTLER: DISCOVERING T...
 
Lutilizzoditwitterinitalianel2012 121214070608-phpapp01
Lutilizzoditwitterinitalianel2012 121214070608-phpapp01Lutilizzoditwitterinitalianel2012 121214070608-phpapp01
Lutilizzoditwitterinitalianel2012 121214070608-phpapp01
 
Rakesh-Nune-Incident-Management-for-DDOT
Rakesh-Nune-Incident-Management-for-DDOTRakesh-Nune-Incident-Management-for-DDOT
Rakesh-Nune-Incident-Management-for-DDOT
 

Similar to IOC in unity

Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
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 CampTheo Jungeblut
 
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 Theo Jungeblut
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampCut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampTheo Jungeblut
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC PrinciplesPavlo Hodysh
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applicationsBabak Naffas
 
Dev Cast Dependency Injection
Dev Cast Dependency InjectionDev Cast Dependency Injection
Dev Cast Dependency InjectionDylan Thomas
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
You Don't Need Dependency Injection
You Don't Need Dependency InjectionYou Don't Need Dependency Injection
You Don't Need Dependency Injectionintive
 
Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Mohammed Salah Eldowy
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesSami Mut
 
Dependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSDependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSRemo Jansen
 

Similar to IOC in unity (20)

Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
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
 
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
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampCut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 
Dev Cast Dependency Injection
Dev Cast Dependency InjectionDev Cast Dependency Injection
Dev Cast Dependency Injection
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
You don't need DI
You don't need DIYou don't need DI
You don't need DI
 
You Don't Need Dependency Injection
You Don't Need Dependency InjectionYou Don't Need Dependency Injection
You Don't Need Dependency Injection
 
Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Assessing Product Line Derivation Operators Applied to Java Source Code: An E...
Assessing Product Line Derivation Operators Applied to Java Source Code: An E...Assessing Product Line Derivation Operators Applied to Java Source Code: An E...
Assessing Product Line Derivation Operators Applied to Java Source Code: An E...
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
 
Dependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSDependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJS
 

Recently uploaded

WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!WSO2
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2
 
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2
 
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfryanfarris8
 
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public AdministrationWSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public AdministrationWSO2
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 

Recently uploaded (20)

WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid Environments
 
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
 
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public AdministrationWSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 

IOC in unity

  • 1. IoC in Microsoft Unity Francesco Garavaglia 03/2016
  • 2. Agenda  The Problem  Composition by Examples  Inversion of Control (IoC)  Dependency Injection Microsoft Unity 2
  • 3. What problems are we trying to solve? 3
  • 4. 4 The 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.  Code quality ( What’s Bad ) R.Martin 1996 - Rigid (hard to modify) - Fragile ( errors occur on almost every change) - Immobile (not reusable) The Problem
  • 5. How? Our solutions should be: • Modular • Testable • Adaptive to change • Whatever you want 5
  • 6. How? Our solutions should be: • Modular • Testable • Adaptive to change • Whatever you want 6
  • 7. 7 We need a glossary  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  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. The Problem
  • 10. 10 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(); } } TextEditor SpellChecker Composition by Examples
  • 11. 11 Ex1: Composition •Simple What is Good •It’s not testable •It’s hard to maintain/change What is Bad Composition by Examples
  • 13. 13 Better approach TextEditor + CheckSpelling() : bool SpellCheckerService + CheckSpelling() : string «interface» ISpellCheckerService + CheckSpelling() : string Dependency Inversion A.High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions. Robert C. Martin 1996 Composition by Examples
  • 14. 14 Context Granny + Eat() : void «interface» IAppleProvider + GetApple() : IApple RedAppleProvider + GetApple() : IApple GoldenAppleProvider + GetApple() : IApple «interface» IPillProvider ConcretePillProvider Context Composition by Examples
  • 15. 15 Ex2:Loose Coupling public class TextEditor { private readonly ISpellCheckerService _spellCheckerService; public TextEditor(ISpellCheckerService spellCheckerService) { _spellCheckerService = spellCheckerService; } public string CheckSpelling() { return _spellCheckerService.CheckSpelling(); } } Composition by Examples
  • 16. 16 Ex2: Unit Testing // Mock ISpellCheckerService mock = new SpellCheckerServiceMock(); // Instantiate TextEditor textEditor = new TextEditor(mock); // Check Assert.AreEqual(“Mock”, textEditor.CheckSpelling()); Composition by Examples
  • 17. 17 Ex2: Good vs Bad • Dependencies are obvious. • Dependency resolution is not encapsulated. • Unit Testing is applicable • Architecture is much better What is Good • We are resolving dependencies manually while creating instances of TextEditor. What is Bad  TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself. Composition by Examples
  • 19. 19
  • 20. 20
  • 21. 21
  • 22. 22
  • 23. 23
  • 24. 24
  • 25. 25 Factory TextEditorFactory + GetEnglishTextEditor() : TextEditor + GetFrenchTextEditor() : TextEditor TextEditor FrenchSpellCheckerServ ice «interface» ISpellCheckerServ ice EnglishSpellCheckerServ ice Composition by Examples
  • 26. 26 What changed  Any required combination of Text Editor and Spell Checking Service is created by object factory. •It’s testable •No manual wiring What is Good •You have to maintain factory or service locator •The more combinations the more methods we have in factory. •Your code knows about the specific factory or factory interface. This means that infrastructure logic is mixed with business logic. •Factory may have states. What is Bad Composition by Examples
  • 27. 27 Ex4: Service Locator Unfortunately, being a kind of Factory, Service Locators suffer from the same problems of testability and shared state. Composition by Examples
  • 28. 28 What are we looking for? Composition by Examples
  • 30. 30 Inversion of Control IoC – is a common characteristic of frameworks. According to Martin Fowler the etymology of the phrase dates back to 1988. Inversion of Control
  • 31. 31 Dependency Injection  DI is a kind of 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. Inversion of Control
  • 32. 32 SpellCheckerService + CheckSpelling() : bool TextEditor + CheckSpelling() : bool «interface» ISpellCheckerService We have already prepared basis Loosely coupled structure Inversion of Control
  • 33. It’s time to introduce new role: Injector Injector (sometimes referred to as a provider or container) 33
  • 35. 35 Ex5: Unity using Microsoft.Practices.Unity; UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); TextEditor textEditor = container.Resolve<TextEditor>(); DI with Unity
  • 36. 36 What changed  Unity container now resolves dependencies •Automated dependency resolution •Business logic and infrastructure are decoupled. What is Good What is Bad DI with Unity
  • 37. 37 Injection Types  Interface injection (by Martin Fowler)  Constructor Injection (by Martin Fowler)  Setter injection (by Martin Fowler)  Method call injection (Unity)  Method decorator injection (Guice) DI with Unity
  • 38. 38 Unity Configuration <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Pr actices.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> DI with Unity
  • 39. 39 Unity Configuration using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; UnityContainer container = new UnityContainer(); container.LoadConfiguration(); TextEditor textEditor = container.Resolve<TextEditor>(); DI with Unity
  • 41. 41 Dependency tree public interface IAdditionalDependency{} public class AdditionalDependency : IAdditionalDependency{} public class SpellCheckingService: ISpellCheckerService { public SpellCheckingService( IAdditionalDependency dependency){} } UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); container.RegisterType<IAdditionalDependency, AdditionalDependency>(); TextEditor textEditor = container.Resolve<TextEditor>(); DI with Unity
  • 42. 42 Dependency tree SpellCheckerService + CheckSpelling() : bool TextEditor + CheckSpelling() : bool «interface» ISpellCheckerService AdditionalDependency + CheckSpelling() : bool «interface» IAditionalDependenct DI with Unity
  • 43. 43 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; } } DI with Unity
  • 44. 44 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>(); DI with Unity
  • 45. 45 Method call injection public class TextEditor { public ISpellCheckerService SpellcheckerService {get; set;} public void Initialize (ISpellCheckerService spellcheckerService) { _spellCheckerService = spellcheckerService; } } UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); TextEditor textEditor = container.Resolve<TextEditor>(); DI with Unity
  • 46. 46 Lifetime Managers  TransientLifetimeManager Returns a new instance of the requested type for each call. (default behavior)  ContainerControlledLifetimeManager Implements a singleton behavior for objects. The object is disposed of when you dispose of the container.  ExternallyControlledLifetimeManager Implements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope.  HierarchicalifetimeManager Implements a singleton behavior for objects. However, child containers don't share instances with parents.  PerResolveLifetimeManager Implements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph.  PerThreadLifetimeManager Implements a singleton behavior for objects but limited to the current thread. DI with Unity
  • 47. 47 Unity Singleton UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(new ContainerControlledLifetimeManager()); TextEditor textEditor = container.Resolve<TextEditor>(); DI with Unity
  • 49. 49 Unity Limitations • When your objects and classes have no dependencies on other objects or classes. • When your dependencies are very simple and do not require abstraction. DI with Unity
  • 50. 50 References  Martin Fowler – Dependency Injection http://martinfowler.com/articles/injection.html  R. Martin - Dependency Inversion principle http://www.objectmentor.com/resources/articles/dip.pdf  Developer's Guide to Dependency Injection Using Unity https://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx