Dependency Injection with Unity
Total Page:16
File Type:pdf, Size:1020Kb
D EPEN DEPENDENCY INJECTION WITH UNITY Over the years software systems have evolutionarily become more and more patterns & practices D ENCY complex. One of the techniques for dealing with this inherent complexity Proven practices for predictable results of software systems is dependency injection – a design pattern that I allows the removal of hard-coded dependencies and makes it possible to Save time and reduce risk on your NJECT assemble a service by changing dependencies easily, whether at run-time software development projects by or compile-time. It promotes code reuse and loosely-coupled design which incorporating patterns & practices, I leads to more easily maintainable and flexible code. Microsoft’s applied engineering ON guidance that includes both production The guide you are holding in your hands is a primer on using dependency quality source code and documentation. W I injection with Unity – a lightweight extensible dependency injection TH DEPENDENCY INJECTION container built by the Microsoft patterns & practices team. It covers The guidance is designed to help U software development teams: various styles of dependency injection and also additional capabilities N I of Unity container, such as object lifetime management, interception, Make critical design and technology TY and registration by convention. It also discusses the advanced topics of selection decisions by highlighting WITH UNITY enhancing Unity with your custom extensions. the appropriate solution architectures, technologies, and Microsoft products The guide contains plenty of trade-off discussions and tips and tricks for for common scenarios managing your application cross-cutting concerns and making the most out of both dependency injection and Unity. These are accompanied by a Understand the most important Dominic Betts real world example that will help you master the techniques. Keep in mind concepts needed for success by that Unity can be used in a wide range of application types such as desktop, explaining the relevant patterns and Grigori Melnik web, services, and cloud. We encourage you to experiment with the sample prescribing the important practices Fernando Simonazzi code and think beyond the scenarios discussed in the guide. Get started with a proven code base Mani Subramanian In addition, the guide includes the Tales from the Trenches – a collection of by providing thoroughly tested case studies that offer a different perspective through the eyes of developers software and source that embodies Microsoft’s recommendations working on the real world projects and sharing their experiences. These Foreword by Chris Tavares chapters make clear the range of scenarios in which you can use Unity, and The patterns & practices team consists also highlight its ease of use and flexibility. of experienced architects, developers, Whether you are a seasoned developer or just starting your development writers, and testers. We work openly journey, we hope this guide will be worth your time studying it. We hope you with the developer community and discover that Unity container adds significant benefits to your applications industry experts, on every project, to ensure that some of the best minds in and helps you to achieve the goals of maintainability, testability, flexibility, the industry have contributed to and and extensibility in your own projects. Happy coding! reviewed the guidance as it is being developed. I’m thrilled to see this book published. For the first time, there’s one place you can look for both the concepts of DI and how to apply those We also love our role as the bridge concepts using the Unity container. between the real world needs of our customers and the wide range of Read the book, embrace the concepts, and enjoy the world of loosely products and technologies that coupled, highly cohesive software that DI makes so easy to build! Microsoft provides. Chris Tavares Microsoft Senior Software Development Engineer and co-creator • • • • • • of Unity • • • • • • • • • • • • • • • For more information explore: • • • • • microsoft.com/practices msdn.com/unity Software Architecture and Software Development Dependency Injection with Unity 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. Contents 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 v 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 Foreword The set of ideas that later congealed into the Unity container were originally conceived