Dependency Injection with Enterprise Library 4.1 - Presentation Transcript
WIN406
Dependency Injection with
Enterprise Library 4.1
Hugo Batista
http://blogs.msdn.com/hugobatista
Microsoft Consulting Services
Session Objectives and
Takeaways
• Session Objective(s):
– Raise awareness about the Dependency
Injection Design Pattern and its applicability
– Provide an overview and demonstrate the
Unity Application Block
• Takeaway:
– Unity facilitates pluggable software and
maintainable designs
Copyright Microsoft Corporation – All rights reserved
Copyright Microsoft Corporation – All rights reserved
Contoso Web App
ShowAllContacts.aspx
TraceLogger Class
ContactsLogic Class
ContactsRepository Class
Contacts
Database
Copyright Microsoft Corporation – All rights reserved
To run this demo offline, check the following solutions:
•WIN406-1.0
demo
CONTOSO WEB APP
What about dependencies?
• How does ShowAllContacts finds its
dependencies?
• What if we need to use a FileLogger
instead?
– And what about using a specific logger for
ContactsLogic?
• What if I need to Mock database
interactions?
– Unit tests
Copyright Microsoft Corporation – All rights reserved
What about dependencies?
• How does ShowAllContacts finds its
dependencies?
• What if weWhat if we need to a FileLogger
need to use
cache the results from
instead? ContactsRepository?
– And what about using a specific logger for
ContactsLogic?
• What if I need to Mock database
interactions?
– Unit tests
Copyright Microsoft Corporation – All rights reserved
What about dependencies?
• How does ShowAllContacts finds its
dependencies?
• What if weWhat if if we need toa FileLogger
need to use
What we need to
instrument
cache the results from
instead? ContactsRepository?
ContactsRepository
– And what about using a specific logger for
operations?
ContactsLogic?
• What if I need to Mock database
interactions?
– Unit tests
Copyright Microsoft Corporation – All rights reserved
Sounds familiar?
• “Unit Tests are hard to write because of
my dependencies”
• “Sorry, we don’t do any customizations on
our Software Products”
• “Logging and Instrumentation will take us
2 more months of development”
• “I can’t start developing that component,
since some dependencies aren’t ready”
Copyright Microsoft Corporation – All rights reserved
We need higher flexibility!
• Pluggable Architectures
• Out-of-the-box Extensibility
Copyright Microsoft Corporation – All rights reserved
Some useful patterns
• Service Locator
.
• (Abstract) Factory
• Builder
• Dependency Injection
Copyright Microsoft Corporation – All rights reserved
Some useful patterns
• Service Locator
.
• (Abstract) Factory
• Builder
• Dependency Injection
A design principle that manages the
colaboration between application
components and services, namely their
dependencies and their lifecycle
Copyright Microsoft Corporation – All rights reserved
Urban Myths around DI
• “That’s too
complicated!”
• “It’s over killing!”
• “It’s slow!”
• “I’ll never need it!”
Copyright Microsoft Corporation – All rights reserved
What is Dependency Injection?
Type Mapping
Configuration
• It is all about wiring up MyClass1Consumer
objects
– Supplying (injecting)
Dependency Container
an external
dependency into a
software component
• Types of Dependency MyClass1 Instance
MyClass1
Injection MyClass2 Instance
MyClass2
– Constructor (most
MyClass3 Instance
popular) MyClass3 Inject
Dependencies
– Property Setter
– Method
Copyright Microsoft Corporation – All rights reserved
What’s so different?
• Object is no longer responsible for finding
its dependencies
• The container does it for you (i.e. resolves
dependencies)
• You express your dependencies explicitly
instead of expressing a dependency on a
service locator
• Pattern is used in a single place
– Usually in some entry point
Copyright Microsoft Corporation – All rights reserved
Unity Application Block
• Enterprise Library DI Container
• Supports common injection approaches
– Constructor Injection
– Property Injection
– Method Call Injection
• Configuration infrastructure
• Highly extensible
• Interception and PIAB integration (Unity 1.2)
• Generics and Arrays support(Unity 1.2)
• Auto-wiring
Copyright Microsoft Corporation – All rights reserved
Unity Container
• Provided by UnityContainer class
(IUnityContainer interface)
• Keeps types and dependencies
configuration
– Mappings
– Lifetime
– Interception
• Implements Fluent Interface
• Your point of contact with Unity
Copyright Microsoft Corporation – All rights reserved
Setting up the Container
IUnityContainer myContainer = new UnityContainer();
//Mapping IMyInterface1 to MyClass1
//Mapping IMyInterface2 to MyClass2
myContainer.RegisterType<IMyInterface1, MyClass1>()
.RegisterType<IMyInterface2, MyClass2>();
Setting up the Container
(Xml Configuration)
<unity>
<containers>
<container>
<types>
<type type=“IMyInterface1, MyAssembly”
mapTo=“MyClass1, MyAssembly“ />
</types>
</container>
</containers>
</unity>
Resolving a Type
IMyInterface1 myObject1 =
myContainer.Resolve<IMyInterface1>();
//resolving using registration name
IMyInterface1 myObject2 =
myContainer.Resolve<IMyInterface1>(“SomeName”);
Building an existing instance
MyClass myObject1 = new MyClass();
myContainer.BuildUp(myObject1);
public class MyClass
{
[InjectionMethod()]
public void Initialize(IMyDependency myDependency)
{
//plumbing code here
}
//....
}
To run this demo offline, check the following
solutions:
•WIN406-2.1
•WIN406-2.2
•WIN406-2.3
•WIN406-2.4
•WIN406-2.5
demo
Decoupling components
REFACTORING CONTOSO
WITH UNITY
Unity Lifetime Managers
• ContainerControlledLifetimeManager
– Singleton behaviour while container lives
• ExternallyControlledLifetimeManager
– Weak Reference “singleton”
• Collected by GC
• PerThreadLifetimeManager
– Singleton behaviour on a per-thread basis
• Custom Lifetime Managers
– LifetimeManager abstract class
Copyright Microsoft Corporation – All rights reserved
Controlling Lifetime
IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<IMyInterface1, MyClass1>(
new ContainerControlledLifetimeManager());
myContainer.RegisterType<IMyInterface2, MyClass2>(
new ExternallyControlledLifetimeManager());
myContainer.RegisterType<IMyInterface3, MyClass3>(
new PerThreadLifetimeManager());
To run this demo offline, check the following
solutions:
•WIN406-3.0
demo
Changing Objects Lifetime - TraceLogger as a Singleton
REFACTORING CONTOSO
WITH UNITY
Unity Interception
• Common behavior injection
– Instrumentation, Authorization, Auditing, Caching, etc..
• Cross cutting concerns clearly separated from
business logic
Container
Resolve/
BuildUp
Call Method or
Get/Set Property
Pre Pre Pre
Interceptor
Handlers Pipeline
Client Object
(Proxy/
Stub) Post Post Post
Copyright Microsoft Corporation – All rights reserved
Unity Interceptors
• Instance Interceptors
– TransparentProxyInterceptor
• .Net TransparentProxy/RealProxy infrastructure
• Object must either implement an interface or inherit
MarshalByRefObject
– InterfaceInterceptor
• Dynamic generated proxy based on interface
• Object must implement an interface
• Type Interceptors
– VirtualMethodInterceptor
• Dynamic generated derived class
• Intercepted methods must be virtual
Copyright Microsoft Corporation – All rights reserved
PIAB Call Handlers
• Authorization
• Caching
• Exception Handling
• Logging
• Performance Counters
• Validation
Copyright Microsoft Corporation – All rights reserved
Setting up Interception
myContainer.Configure<Interception>()
.SetInterceptorFor<IMyInterface1>(
new TransparentProxyInterceptor());
myContainer.Configure<Interception>()
.SetInterceptorFor<IMyInterface2>(
new VirtualMethodInterceptor());
myContainer.Configure<Interception>()
.SetInterceptorFor<IMyInterface3>(
new InterfaceInterceptor());
To run this demo offline, check the following
solutions:
•WIN406-4.0
demo
Using interceptors and PIAB integration – Caching results...
REFACTORING CONTOSO
WITH UNITY INTERCEPTION
Microsoft Confidential
Extending Unity
• Unity Container Extensions
– Base class UnityContainerExtension
– Usually requires OB knowledge
• Policies
• Strategies
– Container configured through
IUnityContainer.AddExtension
• Possible Scenarios
– Custom Resolution
– Automatic Configuration
Copyright Microsoft Corporation – All rights reserved
To run this demo offline, check the following
solutions:
•WIN406-5.0
demo
Default Type Mapping, PIAB Auto Configuration
ADDING EXTENSIONS TO
UNITY
Microsoft Confidential
Advantages of using Unity
• Consistent (and out of the box) Extensibility
• Low impact on existing components
• Lifecycle Management
– To Singleton or Not To Singleton
• Decoupled components
– Dynamic and pluggable architectures
– Increases reusability and testability (a lot!)
• Separation of concerns
– Business Logic versus Infrastructure Logic
Copyright Microsoft Corporation – All rights reserved
When to use Unity?
• Your objects and classes may have
dependencies that:
– Are complex and/or require abstraction
– You might need to Mock up
– You want to be able to configure and change at
runtime (and use a provider model)
• You want to manage the lifetime of object
instances
• You want to implement cross cutting
concerns
Copyright Microsoft Corporation – All rights reserved
Where to use Unity?
• Layered Architectures
• Extensibility Points
• External Components
• Frameworks
• Instrumentation Points
• Mock Objects
• Cross components Validations
– Ex: Argument Validation through Validation Application Block
Copyright Microsoft Corporation – All rights reserved
Unity for Silverlight
• Port of Unity to Silverlight 2.0
• Single Assembly
(Microsoft.Practices.Unity.dll)
• Only public types can be injected
• Xml configuration is not supported
• Interception is not supported
Copyright Microsoft Corporation – All rights reserved
Now what?
• Download Enterprise Library 4.1 / Unity
1.2
• Browse QuickStart Samples
• Check the new HOLs (Feb 2009)
• Start today!
– Adopt Interface pattern when possible
– You can start with Service Locator, then
refactor to DI style
– Constructor Injection is less intrusive
Copyright Microsoft Corporation – All rights reserved
Resources
• Download Enterprise Library and related resources
– http://msdn.microsoft.com/entlib
• Join the Enterprise Library and Unity communities at:
– http://codeplex.com/entlib
– http://codeplex.com/unity
• Unity:
– http://msdn.microsoft.com/unity
• Microsoft patterns & practices catalog
– http://msdn.microsoft.com/practices
• Dependency Injection Design Pattern
– http://martinfowler.com/articles/injection.html
• My blog
– http://blogs.msdn.com/hugobatista
Copyright Microsoft Corporation – All rights reserved
Related Content
• TLA305 – O porquê de desenvolver utilizando
metodologias test driven
• C&T 666– Desenvolvimento Aplicacional Mutável –
Tertúlia
Dia 19, 16:45->17:30, Sala S15
Copyright Microsoft Corporation – All rights reserved
Microsoft Enterprise Library is a collection of reu more
Microsoft Enterprise Library is a collection of reusable application blocks that help address the common problems that software engineers face when developing enterprise applications.
In this deck we cover Unity, the Dependency Container available in Enterprise Library, and we will walk around its possibilities, namely the ones related with application extensibility and dynamic behavior. We will cover the usage of Dependency Injection Design Pattern as a core foundation, allowing high levels of extensibility and maintainability. We will see how we can achieve flexibility by design, building pluggable architectures through very loosely coupled design. Topics covered include DI pattern advantages and disadvantages, usage scenarios, and Unity as a container. less
0 comments
Post a comment