Dependency Injection with Enterprise Library 4.1

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    1 Favorite

    Dependency Injection with Enterprise Library 4.1 - Presentation Transcript

    1. WIN406 Dependency Injection with Enterprise Library 4.1 Hugo Batista http://blogs.msdn.com/hugobatista Microsoft Consulting Services
    2. 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
    3. Copyright Microsoft Corporation – All rights reserved
    4. Contoso Web App ShowAllContacts.aspx TraceLogger Class ContactsLogic Class ContactsRepository Class Contacts Database Copyright Microsoft Corporation – All rights reserved
    5. To run this demo offline, check the following solutions: •WIN406-1.0 demo CONTOSO WEB APP
    6. 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
    7. 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
    8. 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
    9. 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
    10. source: http://geekandpoke.typepad.com http://creativecommons.org/licenses/by-nd/2.0/
    11. We need higher flexibility! • Pluggable Architectures • Out-of-the-box Extensibility Copyright Microsoft Corporation – All rights reserved
    12. Some useful patterns • Service Locator . • (Abstract) Factory • Builder • Dependency Injection Copyright Microsoft Corporation – All rights reserved
    13. 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
    14. 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
    15. 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
    16. 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
    17. 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
    18. 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
    19. Setting up the Container IUnityContainer myContainer = new UnityContainer(); //Mapping IMyInterface1 to MyClass1 //Mapping IMyInterface2 to MyClass2 myContainer.RegisterType<IMyInterface1, MyClass1>() .RegisterType<IMyInterface2, MyClass2>();
    20. Setting up the Container (Xml Configuration) <unity> <containers> <container> <types> <type type=“IMyInterface1, MyAssembly” mapTo=“MyClass1, MyAssembly“ /> </types> </container> </containers> </unity>
    21. Resolving a Type IMyInterface1 myObject1 = myContainer.Resolve<IMyInterface1>(); //resolving using registration name IMyInterface1 myObject2 = myContainer.Resolve<IMyInterface1>(“SomeName”);
    22. Building an existing instance MyClass myObject1 = new MyClass(); myContainer.BuildUp(myObject1); public class MyClass { [InjectionMethod()] public void Initialize(IMyDependency myDependency) { //plumbing code here } //.... }
    23. 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
    24. 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
    25. Controlling Lifetime IUnityContainer myContainer = new UnityContainer(); myContainer.RegisterType<IMyInterface1, MyClass1>( new ContainerControlledLifetimeManager()); myContainer.RegisterType<IMyInterface2, MyClass2>( new ExternallyControlledLifetimeManager()); myContainer.RegisterType<IMyInterface3, MyClass3>( new PerThreadLifetimeManager());
    26. To run this demo offline, check the following solutions: •WIN406-3.0 demo Changing Objects Lifetime - TraceLogger as a Singleton REFACTORING CONTOSO WITH UNITY
    27. 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
    28. 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
    29. PIAB Call Handlers • Authorization • Caching • Exception Handling • Logging • Performance Counters • Validation Copyright Microsoft Corporation – All rights reserved
    30. Setting up Interception myContainer.Configure<Interception>() .SetInterceptorFor<IMyInterface1>( new TransparentProxyInterceptor()); myContainer.Configure<Interception>() .SetInterceptorFor<IMyInterface2>( new VirtualMethodInterceptor()); myContainer.Configure<Interception>() .SetInterceptorFor<IMyInterface3>( new InterfaceInterceptor());
    31. Setting up Interception (Xml Configuration) <interceptors> <interceptor type=“InterceptorType\"> <key type=“MyType1\" /> </interceptor> </interceptors> ... <types> <type type=“MyType1” mapTo=“MyType2“ /> </types>
    32. 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
    33. 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
    34. 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
    35. 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
    36. 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
    37. 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
    38. 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
    39. 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
    40. 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
    41. 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
    42. Q&A
    SlideShare Zeitgeist 2009

    + hbatistahbatista Nominate

    custom

    1436 views, 1 favs, 0 embeds more stats

    Microsoft Enterprise Library is a collection of reu more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 1436
      • 1436 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 1
    • Downloads 2
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories