dependency injection with unity

142 265 0
dependency injection with unity

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

For more information explore: microsoft.com/practices msdn.com/unity Software Architecture and Software Development patterns & practices Proven practices for predictable results Save time and reduce risk on your software development projects by incorporating patterns & practices, Microsoft’s applied engineering guidance that includes both production quality source code and documentation. The guidance is designed to help software development teams: Make critical design and technology selection decisions by highlighting the appropriate solution architectures, technologies, and Microsoft products for common scenarios Understand the most important concepts needed for success by explaining the relevant patterns and prescribing the important practices Get started with a proven code base by providing thoroughly tested software and source that embodies Microsoft’s recommendations The patterns & practices team consists of experienced architects, developers, writers, and testers. We work openly with the developer community and industry experts, on every project, to ensure that some of the best minds in the industry have contributed to and reviewed the guidance as it is being developed. We also love our role as the bridge between the real world needs of our customers and the wide range of products and technologies that Microsoft provides. DepenDency InjectIon wIth UnIty •••••• •••••••• ••••••• ••••• De p e n D e n c y In j e c t I o n w I t h Un I t y Dominic Betts Grigori Melnik Fernando Simonazzi Mani Subramanian Foreword by Chris Tavares DepenDency InjectIon wIth UnIty Overtheyearssoftwaresystemshaveevolutionarilybecomemoreandmore complex.Oneofthetechniquesfordealingwiththisinherentcomplexity of software systems is dependency injection – a design pattern that allowstheremovalofhard-codeddependenciesandmakesitpossibleto assembleaservicebychangingdependencieseasily,whetheratrun-time orcompile-time.Itpromotescodereuseandloosely-coupleddesignwhich leadstomoreeasilymaintainableandexiblecode. Theguideyouareholdinginyourhandsisaprimeronusingdependency injection with Unity – a lightweight extensible dependency injection container built by the Microsoft patterns & practices team. It covers various styles of dependency injection and also additional capabilities of Unity container, such as object lifetime management, interception, and registration by convention. It also discusses the advancedtopics of enhancingUnitywithyourcustomextensions. Theguidecontains plentyoftrade-offdiscussions andtipsand tricksfor managing your application cross-cutting concerns and making themost outofbothdependencyinjectionandUnity.Theseareaccompaniedbya realworldexamplethatwillhelpyoumasterthetechniques.Keepinmind thatUnitycanbeusedinawiderangeofapplicationtypessuchasdesktop, web,services,andcloud.Weencourageyoutoexperimentwiththesample codeandthinkbeyondthescenariosdiscussedintheguide. Inaddition,theguideincludestheTalesfromtheTrenches–acollectionof casestudiesthatofferadifferentperspectivethroughtheeyesofdevelopers working on the realworld projects and sharing their experiences. These chaptersmakecleartherangeofscenariosinwhichyoucanuseUnity,and alsohighlightitseaseofuseandexibility. Whetheryouareaseasoneddeveloperorjuststartingyourdevelopment journey,wehopethisguidewillbeworthyourtimestudyingit.Wehopeyou discoverthatUnitycontaineraddssignicantbenetstoyourapplications andhelpsyoutoachievethegoalsofmaintainability,testability,exibility, andextensibilityinyourownprojects.Happycoding! I’m thrilled to see this book published.For the rst time, there’s one placeyoucanlookforboththeconceptsofDIandhowtoapplythose conceptsusingtheUnitycontainer. Readthebook,embracetheconcepts,andenjoytheworldofloosely coupled,highlycohesivesoftwarethatDImakessoeasytobuild! Chris Tavares Microsoft Senior Software Development Engineer and co-creator of Unity D I  U Dependency Injection with Unity Dominic Betts Grigori Melnik Fernando Simonazzi Mani Subramanian Foreword by Chris Tavares ISBN: 978-1-62114-028-3 This document is provided “as-is”. Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. Some examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred. This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. © 2013 Microsoft. All rights reserved. Microsoft, Visual Basic, Visual Studio, Windows, and Windows Server are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.  Foreword ix Preface xi About This Guide xi Who This Book Is For xii What Do You Need to Get Started? xii Who’s Who xii Motivations 1 Maintainability 1 Chapter 1: Introduction 1 Testability 2 Flexibility and Extensibility 2 Late Binding 2 Parallel Development 3 Crosscutting Concerns 3 Loose Coupling 3 A Simple Example 3 When Should You Use a Loosely Coupled Design? 7 Principles of Object-Oriented Design 8 Single Responsibility Principle 8 The Open/Closed Principle 8 The Liskov Substitution Principle 8 Interface Segregation Principle 9 Dependency Inversion Principle 9 Summary 10 More Information 10 Contents vi Chapter 2: Dependency Injection 11 Introduction 11 Factories, Service Locators, and Dependency Injection 11 Factory Patterns 11 The Factory Method Pattern 11 Simple Factory Pattern 13 Abstract Factory Pattern 14 Service Locator Pattern 14 Dependency Injection 15 Object Composition 17 Object Lifetime 17 Types of Injection 18 Property Setter Injection 18 Method Call Injection 19 When You Shouldn’t Use Dependency Injection 19 Summary 20 More Information 20 Chapter 3: Dependency Injection with Unity 21 Introduction 21 The Dependency Injection Lifecycle: Register, Resolve, Dispose 21 Register 22 Resolve 22 Dispose 23 Registering and Resolving in your Code 23 Adding Unity to Your Application 23 A Real-World Example 24 Type Registrations in the Example 26 Instance Registration 26 Simple Type Registration 27 Constructor Injection 27 Registering Open Generics 28 Parameter Overrides 29 Resolving Types in the Example 29 Simple Resolve 29 Resolving in an MVC Application 30 Using the Per Request Lifetime Manager in MVC and WebAPI Application 30 Resolving with Run Time Information 31 Registration 32 Named Type Registrations 32 Design-Time Configuration 33 Registration by Convention 34 Registration by Convention and Generic Types 38 Using Child Containers 38 Viewing Registration Information 39 vii Resolving 41 Resolving in an ASP.NET Web Application 41 Resolving in a WCF Service 43 Using the UnityServiceHost Class with a Self-hosted Service 46 Using the UnityServiceHost Class with Service Hosted in IIS or WAS 47 Automatic Factories 47 Deferred Resolution 50 Lifetime Management 51 Hierarchical Lifetime Management 52 Per Resolve Lifetime Management 53 Externally Controlled Lifetime Management 55 Per Request Lifetime Management 55 Per Thread Lifetime Management 56 Dependency Injection and Unit Testing 56 Summary 58 More Information 58 Chapter 4: Interception 59 Introduction 59 Crosscutting Concerns 59 The Decorator Pattern 60 Using Unity to Wire Up Decorator Chains 63 Aspect Oriented Programming 63 Interception 64 Instance Interception 64 Type Interception 65 Summary 66 More Information 66 Chapter 5: Interception using Unity 67 Introduction 67 Crosscutting Concerns and Enterprise Library 67 Interceptors in Unity 67 Configuring the Unity Container to Support Interception 68 Defining an Interceptor 68 Registering an Interceptor 71 Using an Interceptor 72 Alternative Interception Techniques 73 Instance Interception/Type Interception 73 Using the TransparentProxyInterceptor Type 73 Using the VirtualMethodInterceptor Type 74 Using a Behavior to Add an Interface to an Existing Class 76 Interception Without the Unity Container 77 Design Time Configuration 78 Policy Injection 79 Policy Injection and Attributes 83 Policy Injection and the Enterprise Library Blocks 85 A Real World Example 87 Summary 89 More Information 89 viii Chapter 6: Extending Unity 91 Introduction 91 Creating Custom Lifetime Managers 91 Lifetime Managers and Resolved Objects 92 Extending the SynchronizedLifetimeManager Type 92 Extending the LifetimeManager Type 95 Extending the Unity Container 96 Without the Event Broker Container Extension 96 With the Event Broker Extension 97 Implementing the Simple Event Broker 98 Implementing the Container Extension 100 Discovering the Publishers and Subscribers 101 Wiring Up the Publishers and Subscribers 103 Summary 104 More Information 104 Summary 105 Tales from the Trenches: Using Unity 107 Tales from the Trenches: One User’s Story —Customizing Unity 111 More Information 115 Tales from the Trenches: Using Unity in a Windows Store app 116 AdventureWorks Shopper 116 References 117 More Information 117 Appendix A: Unity and Windows Store apps 119 The UnityServiceLocator Class 119 Unity Design-time Configuration 119 Unity Interception 119 More Information 119 Index 121  The set of ideas that later congealed into the Unity container were originally conceived while I was working on the Web Client Software Factory project. Microsoft’s patterns & practices team had been using the concept of dependency injection for several years at that point, most famously in the Composite Application Block (CAB). It was also core to the configuration story in Enterprise Library 2.0, and was again central when we started tackling composite applications for the web (a library that became known as CWAB). Our goal had always been to promote the concepts of Dependency Injection as a way to build loosely coupled systems. However, the way p&p approached DI at the time was different then how we think about it now. In- stead of a single reusable container it was felt that the DI implementation should be specialized to the system in which it was being used. We used a library called ObjectBuilder, which was described as “a framework to build DI containers.” This would in theory let us write a container per project that did exactly what we wanted. A lofty aspiration, but in practice it didn’t work out so well. ObjectBuilder was a highly decoupled, abstract set of parts that had to be manually assembled. Combined with a lack of documentation it took a lot of time to understand what needed to go where and how to put it together into something useful. That turned into time spent writing, debugging, and optimizing the DI container instead of working on our actual project require- ments. It got even more fun when somebody wanted to use CAB (which used one DI container based on one version of ObjectBuilder) and Enterprise Library (with a separate container based on a different version of Object- Builder) in the same project. Integration was very difficult; just dealing with referencing two different versions of ObjectBuilder in the same project was a challenge. Also the one-off containers led to one-off extensibility and integration interfaces: what worked in Enterprise Library was useless in CAB and vice versa. It finally came to a head when we’d just spent yet another week near the end of the Web Client Software Factory project fixing a bunch of bugs in CWAB: bugs that looked very similar to ones we’d fixed before in CAB. Wouldn’t it be nice, we asked, if we could just have one container implementation and just use it instead of writing them over and over again? From this frustration grew Unity. The Enterprise Library 4.0 team put the Dependency Injection Application Block (as Unity used to be known originally) on the product backlog. Our goals for the project were straight- forward. First, introduce and promote the concepts of dependency injection to our community, unencumbered by a lot of low-level implementation details. Second, have a core container with an easy to use API that we, other teams at Microsoft, or anyone whose organization was uncomfortable using the available open source projects (for whatever reason) could just use. Third, have a variety of extensibility mechanisms so that new features could be added by anyone without having to rip open the core code. In my opinion Unity has succeeded on all these goals. I’m particularly proud of how we affected the .NET de- veloper community. Unity quickly became one of the most commonly used DI containers in the .NET ecosys- tem. More importantly, other DI container usage has increased as well. Unity introduced DI to a new set of people who would have otherwise never heard of it. Some of them later moved on to other containers that better suited their needs. That’s not a loss for Unity: they’re using the concepts, and that’s the important part. Foreword [...]... with chapters that address the specifics of using Unity in your own applications If you’re already familiar with concepts such as dependency injection and interception, you can probably focus on Chapter 3, Dependency Injection with Unity, ” Chapter 5, “Interception with Unity, ” and Chapter 6, “Extending Unity. ” The first two chapters introduce the conceptual background and explain what dependency injection. .. ManagementController class DependencyInjectionContainer class TenantStore class ITenantStore interface Figure 2 Dependencies when using dependency injection Chapter 3, Dependency Injection with Unity, ” will describe in more detail what happens in the DependencyInjectionContainer class Dependency Injection 17 The key difference between the Figure 1 and Figure 2 is the direction of the dependency from the... resources available with the Unity 3 release to help you to learn about Unity, learn about some of the problems and issues that Unity can help you to address, and get started using Unity in your applications Unity is primarily a dependency injection container and so the guide also contains an introduction to dependency injection that you can read in isolation even if you don’t plan to use Unity, although... describes the role of dependency injection as a technique to support loosely coupled designs, and Chapter 3 describes how Unity helps you to implement dependency injection in your applications When Should You Use a Loosely Coupled Design? Loose coupling doesn’t necessarily imply dependency injection, although the two often do go together Before we move on to dependency injection and Unity, you should start... dependency injection and Unity are designed to help you address This introductory chapter will not say much about Unity, or indeed say much about dependency injection, but it will provide some necessary background information that will help you to appreciate the benefits of dependency injection as a technique and why Unity does things the way it does The next chapter, Chapter 2, Dependency Injection, ”... how you can use the Unity container to manage the instantiation of dependent objects and their lifetime More Information All links in this book are accessible from the book’s online bibliography available at: http://aka.ms/unitybiblio 3 Dependency Injection with Unity Introduction In previous chapters, you saw some of the reasons to use dependency injection and learned how dependency injection differs... does things the way it does The next chapter, Chapter 2, Dependency Injection, ” will show you how dependency injection can help you meet the requirements outlined in this chapter, and the following chapter, Chapter 3, Dependency Injection with Unity, ” shows how Unity helps you to implement the dependency injection approach in your applications Motivations When you design and develop software systems,... use the Unity dependency injection container to easily add a dependency injection framework to your applications On the way, you’ll see some examples that illustrate how you might use Unity in a real-world application The Dependency Injection Lifecycle: Register, Resolve, Dispose In the previous chapter, you saw how the ManagementController class has a constructor that expects to be injected with an... apps.” What are the downsides to using Dependency Injection? On StackOverflow tion into a legacy application that was not built with inversion of control in mind Dependency injection promotes a specific style of layering and decoupling in a system that may pose challenges if you try to adapt an existing application, especially with an inexperienced team • Dependency injection is far less important in functional... particular, how and where you might use dependency injection in your own applications In Figure 2, the DependencyInjectionContainer class may manage the dependencies of multiple high level client classes such as the ManagementController class on multiple service classes such as the TenantStore class You can use either a dependency injection container or implement dependency injection manually using factories . 3, Dependency Injection with Unity, ” Chapter 5, “Interception with Unity, ” and Chapter 6, “Extending Unity. ” The first two chapters introduce the conceptual background and explain what dependency. Pattern 14 Dependency Injection 15 Object Composition 17 Object Lifetime 17 Types of Injection 18 Property Setter Injection 18 Method Call Injection 19 When You Shouldn’t Use Dependency Injection. this chapter, and the following chapter, Chapter 3, Dependency Injection with Unity, ” shows how Unity helps you to implement the dependency injection approach in your applications. Motivations When

Ngày đăng: 20/10/2014, 14:03

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan