ineta Solutions Architect & Trainer Microsoft MVP (10 years and running!) ASP Insider VSX...

41

Transcript of ineta Solutions Architect & Trainer Microsoft MVP (10 years and running!) ASP Insider VSX...

Deep Dive Into Dependency Injection and Writing Decoupled Quality and Testable CodeMiguel A. Castro | @miguelcastro67

ineta

Miguel A. Castro

Solutions Architect & 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

Author of Pluralsight courses:• Building End-to-End Multi-Client Service Oriented

ApplicationsKnockout & Angular Editions

• Developing Extensible Software

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

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

Class used to obtain instance of another class

Wraps the access to DI containerMarker interface (for resolved classes) can be added for generic-constraint (IProcessor)Locator class itself abstracted and injected into consumer

Service Locator

demo 2

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 3

Singleton & Lifetime Scope control

Vary from container to containerMost offer discovery registration

Assembly scanning

Some containers offer rich DSLOther features include Configuration definition

Advanced Registration Feature

demo 4 & 5

Assembly scanning & Module usage

Sometimes need to register > 1 class to interfaceCan label each registration

Resolve by name (kinda dirty usage)

Can inject list of interface-typeMore common usage

One-to-Many Registrations

demo 6

One-to-Many dependencies

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 7

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

Dependency resolver gets hit post-constructor-selector

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 formsCan use a custom page handler factory

Need to run in a “classic .net” app-pool

Easier with custom Page base classTesting 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

Eliminating newing-up inside classesInject into class or use service locator (on-demand)

DI Containers assist in managing components to be used

In most cases, more than “assist” – absolutely essential

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

Resources

Learning

Microsoft Certification & Training Resources

www.microsoft.com/learning

Developer Network

http://developer.microsoft.com

TechNet

Resources for IT Professionals

http://microsoft.com/technet

Sessions on Demand

http://channel9.msdn.com/Events/TechEd

Please Complete An Evaluation FormYour input is important!TechEd Schedule Builder CommNet station or PC

TechEd Mobile app

Phone or Tablet

© 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.

Miguel A. [email protected]

@miguelcastro67www.melvicorp.com

Stay in touch…