Slide 1

Slide 1 text

Unity

Slide 2

Slide 2 text

SOLID: Dependency inversion principle • Entities must depend on abstractions, not on concretions

Slide 3

Slide 3 text

Dependency Injection • Dependency injection is a technique whereby one object supplies the dependencies of another object. • A dependency is an object that can be used (a service). • An injection is the passing of a dependency to a dependent object (a client) that would use it. • The service is made part of the client's state.

Slide 4

Slide 4 text

public interface ISpellChecker { bool CheckSpelling(); } public class SpellChecker : ISpellChecker { public bool CheckSpelling() { throw new NotImplementedException(); } } Interfaces

Slide 5

Slide 5 text

public class TextEditorNoDi { private readonly SpellChecker _spellChecker; public TextEditorNoDi() { _spellChecker = new SpellChecker(); } private void CheckSpelling() { _spellChecker.CheckSpelling(); } } Poor mans DI

Slide 6

Slide 6 text

public class TextEditor { private readonly ISpellChecker _spellChecker; public TextEditor(ISpellChecker spellChecker) { _spellChecker = spellChecker; } private void CheckSpelling() { _spellChecker.CheckSpelling(); } } Constructor Injection

Slide 7

Slide 7 text

var container = new UnityContainer(); container.RegisterType(new HierarchicalLifetimeManager()); var demoA = container.Resolve(); Unity

Slide 8

Slide 8 text

public class Child : IChild { } public class Parent : IParent { public Parent(IChild child) { } } private void Demo() { var container = new UnityContainer(); container.RegisterType(); container.RegisterType(); var parent = container.Resolve(); } Dependency Tree

Slide 9

Slide 9 text

LifetimeManagers • 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

Slide 10

Slide 10 text

LifetimeManagers • 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

Slide 11

Slide 11 text

Demo https://github.com/staal-it/UnityDemo