SlideShare a Scribd company logo
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 Presentation
Dmitry Buzdin
 
Deployment
DeploymentDeployment
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
Fahad 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 Company
PVS-Studio
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Anand Kumar Rajana
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
JMockit
JMockitJMockit
JMockit
Angad Rajput
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
Mario Peshev
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
Marian Wamsiedel
 
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
Denilson Nastacio
 
Dependency Injection in Episerver and .Net
Dependency Injection in Episerver and .NetDependency Injection in Episerver and .Net
Dependency Injection in Episerver and .Net
Valdis Iljuconoks
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
SAP Testing Training
SAP Testing TrainingSAP Testing Training
SAP Testing Training
VGlobal 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 frameworks
EndranNL
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_test
Masanori Kato
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy
 
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
James Phillips
 
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
Marian Wamsiedel
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
Roy Antony Arnold G
 

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
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
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
 
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

IOC in unity
IOC in unityIOC in unity
IOC in unity
Francesco Garavaglia
 
Workshop - cqrs brief introduction
Workshop - cqrs brief introductionWorkshop - cqrs brief introduction
Workshop - cqrs brief introduction
Francesco Garavaglia
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
Remik 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 progetto
Microsoft Mobile Developer
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
chhabraravish23
 
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 @ CD2008
Mauro Servienti
 
IM value creation paper
IM value creation paperIM value creation paper
IM value creation paper
Felix Schlumpf
 
New features cognos10.2
New features cognos10.2New features cognos10.2
New features cognos10.2
Jan van Otten
 
Gadgets as Gifts: What to Consider Before You Buy
Gadgets as Gifts: What to Consider Before You BuyGadgets as Gifts: What to Consider Before You Buy
Gadgets as Gifts: What to Consider Before You Buy
Tom Musbach
 
DIY retailer 2015 winners and losers - Home Hardware Conference
DIY retailer 2015 winners and losers - Home Hardware ConferenceDIY retailer 2015 winners and losers - Home Hardware Conference
DIY retailer 2015 winners and losers - Home Hardware Conference
Insight Retail Group Ltd
 
TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015
TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015
TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015
Kirill Klip
 
how_graphs_eat_the_world
how_graphs_eat_the_worldhow_graphs_eat_the_world
how_graphs_eat_the_world
Ora Weinstein
 
110929 woon+ corporatieplein
110929 woon+ corporatieplein110929 woon+ corporatieplein
110929 woon+ corporatieplein
Roeland Weijs
 
Can junior
Can   juniorCan   junior
Can junior
Dora Kouri
 
Akar masalah papua
Akar masalah papuaAkar masalah papua
Akar masalah papuayance iyai
 
2016-1B-Nune
2016-1B-Nune2016-1B-Nune
2016-1B-Nune
Rakesh Nune
 
Plantilla trabajo aplicaciones de materiales - Empaques de agua
Plantilla trabajo aplicaciones de materiales - Empaques de aguaPlantilla trabajo aplicaciones de materiales - Empaques de agua
Plantilla trabajo aplicaciones de materiales - Empaques de agua
cvargas74
 

Viewers also liked (20)

IOC in unity
IOC in unityIOC in unity
IOC in unity
 
Workshop - cqrs brief introduction
Workshop - cqrs brief introductionWorkshop - cqrs brief introduction
Workshop - cqrs brief introduction
 
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
 
IM value creation paper
IM value creation paperIM value creation paper
IM value creation paper
 
Next pre2
Next pre2Next pre2
Next pre2
 
New features cognos10.2
New features cognos10.2New features cognos10.2
New features cognos10.2
 
Gadgets as Gifts: What to Consider Before You Buy
Gadgets as Gifts: What to Consider Before You BuyGadgets as Gifts: What to Consider Before You Buy
Gadgets as Gifts: What to Consider Before You Buy
 
DIY retailer 2015 winners and losers - Home Hardware Conference
DIY retailer 2015 winners and losers - Home Hardware ConferenceDIY retailer 2015 winners and losers - Home Hardware Conference
DIY retailer 2015 winners and losers - Home Hardware Conference
 
TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015
TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015
TNR Gold Shotgun Gold Project, Alaska. Presentation August 2015
 
how_graphs_eat_the_world
how_graphs_eat_the_worldhow_graphs_eat_the_world
how_graphs_eat_the_world
 
110929 woon+ corporatieplein
110929 woon+ corporatieplein110929 woon+ corporatieplein
110929 woon+ corporatieplein
 
Can junior
Can   juniorCan   junior
Can junior
 
Akar masalah papua
Akar masalah papuaAkar masalah papua
Akar masalah papua
 
2016-1B-Nune
2016-1B-Nune2016-1B-Nune
2016-1B-Nune
 
Plantilla trabajo aplicaciones de materiales - Empaques de agua
Plantilla trabajo aplicaciones de materiales - Empaques de aguaPlantilla trabajo aplicaciones de materiales - Empaques de agua
Plantilla trabajo aplicaciones de materiales - Empaques de agua
 

Similar to IOC in Unity

Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
meghantaylor
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
James Phillips
 
Tdd,Ioc
Tdd,IocTdd,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
Theo 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 Camp
Theo Jungeblut
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
Pavlo 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 Osnabrueck
Theo Jungeblut
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
Shahriar Hyder
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
Babak Naffas
 
Dev Cast Dependency Injection
Dev Cast Dependency InjectionDev Cast Dependency Injection
Dev Cast Dependency Injection
Dylan Thomas
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
Animesh Kumar
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz lin
 
You don't need DI
You don't need DIYou don't need DI
You don't need DI
Sebastian Świerczek
 
You Don't Need Dependency Injection
You Don't Need Dependency InjectionYou Don't Need Dependency Injection
You Don't Need Dependency Injection
intive
 
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 & JSF
Jiayun Zhou
 
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...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
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
Sami 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 InversifyJS
Remo 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

Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 

Recently uploaded (20)

Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 

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