Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Microsoft Unity

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

Microsoft Unity

Presentation and demo about Microsoft Unity Dependency Injection Framework

Source can be found here: https://github.com/staal-it/UnityDemo

Avatar for Erwin Staal

Erwin Staal

July 05, 2017
Tweet

More Decks by Erwin Staal

Other Decks in Programming

Transcript

  1. 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.
  2. public interface ISpellChecker { bool CheckSpelling(); } public class SpellChecker

    : ISpellChecker { public bool CheckSpelling() { throw new NotImplementedException(); } } Interfaces
  3. public class TextEditorNoDi { private readonly SpellChecker _spellChecker; public TextEditorNoDi()

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

    spellChecker) { _spellChecker = spellChecker; } private void CheckSpelling() { _spellChecker.CheckSpelling(); } } Constructor Injection
  5. public class Child : IChild { } public class Parent

    : IParent { public Parent(IChild child) { } } private void Demo() { var container = new UnityContainer(); container.RegisterType<IChild, Child>(); container.RegisterType<IParent, Parent>(); var parent = container.Resolve<IParent>(); } Dependency Tree
  6. 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
  7. 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