ineta .net architect, developer, & trainer microsoft mvp (10 years and running!) asp insider ...
TRANSCRIPT
Deep Dive Into Dependency Injection and Writing Decoupled Quality and Testable CodeMiguel A. Castro | @miguelcastro67
DEV-B412
ineta
Miguel A. Castro
.NET Architect, Developer, & Trainer Microsoft MVP (10 years and running!) ASP Insider VSX Insider C# Insider Azure Insider Member of the INETA Speakers Bureau Conference SpeakerWriting code since 1979
Classes, Dependencies, and CouplingTestingDI Explained & DemoedDI ContainersDI Container Usage: simple & advanceReal-world Usage Scenarios
WPF / Silverlight / WinRTASP.NET MVCASP.NET WebFormsWCF
Agenda
Breaking a life-long habit
One class depending on anotherCannot exist (compile) without other class
Limits functionality to single implementationIf classes perform DB work, difficult to test without hitting DB
Class coupling (why it’s bad)
The secret to writing testable software:Stop “newing-up” objects in a class!
Define dependencies as interfacesListed as constructor args (or properties)
Calling class can sends in instancesLater done by a DI container automatically
Unit tests can send in MocksOr test versions
Embrace abstractions
Demo
Esentials (coupled, abstracted, and testing)
DI: Concepts & Products
An architectural pattern designed to easily satisfy a class’ dependencies
Allows us to write decoupled codeFacilitate testabilityEase deployment of components
Typically implemented with the aid of an object container
What is Dependency Injection
A repository for definitions typically relating an abstraction to a concrete classCore functionality
Provide facility for registering classesUsually related to interfaces
Provide facility for resolving a requestUsually from a given interface (not always)
The DI Container
Type associations (registrations) achieved depending on container
Procedural (fluent interface)Unity, NInject, Castle Windsor, StructureMap, Autofac
ConfigurationSpring.NET, Autofac, etc.
Declarative (attributes)Managed Extensibility Framework (MEF)
The DI Container
Recursively resolves dependenciesInjected interface variables
Constructor (usual)Property
Requesting one class (from container) starts chain reaction
The DI Container
UnityNinjectCastle WindsorStructureMapAutoFac *MEFSpring.NET
Available Containers
demo 1
Using the DI Container
Other DI Techniques
Sometimes a class receives many injectionsMay need only a few (or one), depending on method called
Services or Business engines receiving Data Repositories
Can use locator to obtain instance from container
Service locator ensures testability (or abstract factory)
On-Demand Instances
Can be specific [to a type]Billing Processor Locator
Generic-based (to handle many classes)Processor LocatorMarker interface can be added for generic-constraint (IProcessor)
Service Locator
demo 2 & 3
Using service locator
Transient is typically default for most containers
Not MEFResolved instance kept until parent goes away
Singleton (shared) kept around until container goes away
Every resolve request results in same instance
Instance Lifetime
DI containers hold onto resolved instancesDon’t really know when you called Dispose on them
Released when container is disposedUsually equates to application termination
Some contexts require more release controlWeb context
Disposable Components
Some containers offer helpAutofac is great for thisILifetimeScope creation fom containerInstancePerLifetimeScope / InstancePerRequest upon registrationAutomatically happens in MVC Autofac dependency resolver
Others require a sub-container hack
Disposable Components
demo 4
Singleton & Lifetime Scope control
Sometimes need to register > 1 class to interfaceCan label each registration
Resolve by name (kinda dirty usage)
Can inject list of interface-type
One-to-Many Registrations
demo 5 & 6
Assembly scanning & Module usage
Vary from container to containerMost offer discovery registration
Assembly scanning
Some containers offer rich DSLOther features include Configuration definition
Advanced Registration Feature
demo 7
One-to-Many dependencies
Allows you to skip registrationKick off resolve process AFTER class instantiatedUseful when something else needs to create class
WCF (can be handled through Instance Provider)MVC or API Controllers (can be handled through Dependency Resolver)These two examples are no longer a good example of this
Will need to use Property InjectionTies class to DI container
Can be creative with abstraction to solve coupling
Post-Construction Resolve
demo 8
Post-Construction Resolve & Property Injection
DI containers have different techniques for deciding which constructor to useAutofac picks constructor with most [registered] argumentsMay not always be feasibleA “Contructor Finder” lets you decide how to decide on a constructor
IConstructorFinder interfaceFindConstructorWith extension-method
Deterministic Constructor Injection
demo 9
• Deterministic Constructor Injection
DI Usage Scenarios
Used to resolve ViewModel classesUsed to resolve dependencies injected into ViewModelsUsed to resolve nested ViewModels
ViewModels can be tested and test dependency implementations usedAdvanced scenario: abstract ViewModel contents out
DI in WPF / Silverlight / WinRT
Used to resolve controller classesUsed to resolve injected dependencies into controllers
Can use a custom controller factory or dependency resolver (recommended)Controllers can be tested and test dependency implementations usedMost DI containers have NuGet integration package
DI in ASP.NET MVC & Web API
Used to resolve injected dependencies into requested web formsUses a custom page handler factoryNeed to run in a “classic .net” app-poolTesting code-behind classes still troublesome
DI in ASP.NET WebForms
Need to set up Instance ProviderService Behavior installs itServices can use constructor injectionMost DI containers have NuGet integration package
DI in WCF
demo
Usage Scenarios
The core principle of testable code is usage of interfaces to build decoupled components
No newing-up inside classesInject into class or use service locator (on-demand)
DI Containers assist in managing components to be used
Conclusion
Containers offer different featuresFor most part, all accomplish the same thingChoose the one that you likeAutofac IMO is the more capable and modern one out there
A DI container does NOT facilitate testingThe DI concepts do
Conclusion
Dependency Injection in .NETMark Seemann – Manning
Martin Fowler’s DI/IoC articlehttp://martinfowler.com/articles/injection.html
Tons of info on the web
References
Visit the Developer Platform & Tools BoothHaving a friend buy your coffee?Yea, it’s kind of like that.
MSDN Subscribers get up to $150/mo in Azure credits.
Stop by the Developer Platform and Tools booth and visit the MSDN Subscriptions station to activate your benefits and receive a gift!
http://aka.ms/msdn_teched
3 Steps to New Gear! With Application Insights
1. Create a Visual Studio Online account http://visualstudio.com
2. Install Application Insights Tools for Visual Studio Online http://aka.ms/aivsix
3. Come to our booth for a t-shirt and a chance to win!
VSIP QR Tag Contests Visit our booth to join the hunt for cool prizes!
ResourcesMicrosoft Engineering Stories
How Microsoft Builds Softwarehttp://aka.ms/EngineeringStories
Visual Studio Industry Partner Program
Meet Our New Visual Studio Online Partners or Join Now.http://vsipprogram.com
Visual Studio | Integrate
Create Your Own Dev Environmenthttp://integrate.visualstudio.com
Development tools & services for teams of all sizeshttp://www.visualstudio.com
Complete an evaluation and enter to win!
Evaluate this session
Scan this QR code to evaluate this session.
© 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.