.NET 相依性注入
.NET 相依性注入
使用 Unity
關於本書
邁向專業開發人員之路...
本書內容是關於.NET相依性注入(dependency injection;簡稱DI)的相關議題。透過本書,您將會瞭解:
- 什麼是 DI、它有什麼優點、何時使用 DI、以及可能碰到的陷阱。
- 如何運用 DI 應付容易變動的軟體需求,設計出更彈性、更好維護的程式碼。
- 與 DI 有關的設計模式。
- DI 於 .NET 應用程式中的實務應用,包括 ASP.NET MVC、ASP.NET Web API等等。
- 如何使用 DI 容器(例如 Unity)來協助開發應用程式。
本書的範例皆以C#撰寫,讀者無須具備任何 DI 背景知識。
這不是 .NET 程式設計的入門書。為了避免讀者花錢買了不適合自己的書,容筆者斗膽列舉閱讀本書的基本條件:
- 熟悉 C# 語法,包括擴充方法(extrension methods)、泛型(generics)、委派(delegates)等等。如果精通的是 VB(或其他 .NET 語言)但不排斥 C# 語法,也是 OK 的。
- 具備物件導向的基礎概念,知道何謂封裝、繼承、多型(polymorphism)。
倒不是說,不符合以上條件的讀者就無法從本書汲取有用的東西;只是就一般的情況而言,讀起來會比較辛苦一些。
如果您曾經接觸、研究過設計模式(design patterns),有些章節閱讀起來會輕鬆一些。然而這並非基本要求,因為本書也會一併介紹相關的設計模式與原則,例如 Decorator 模式、Factory 模式、開放/封閉原則(Open/Closed Principle)、單一責任原則(Single Responsibility Principle)等等。
此外,如果下列描述有一些符合您現在的想法,那麼本書也許對您有幫助:
- 我的日常開發工作需要設計共用的類別庫或框架,供他人使用。
- 我經常使用第三方(third-party)元件或框架,而且它們都提供了某種程度的 DI 機制。為了充分運用這些機制,我必須了解 DI 的各種用法。
- 我希望能夠寫出寬鬆耦合、容易維護的程式碼。
- 我已經開始運用寬鬆耦合的設計原則來寫程式,我想知道更多有關 DI 的細節,以了解有哪些陷阱和迷思,避免設計時犯了同樣的毛病。
無論別人怎麼說,自己讀過的感覺最準。強烈建議您先讀完本書的試閱章節(包含本書前言和第 1 章完整內容),以評估這本書是否適合你。
Bundles that include this book
書籍目錄
-
- 序
- 致謝
-
關於本書
- 誰適合閱讀本書
- 如何閱讀本書
- 書寫慣例
- 需要準備的工具
- 範例程式與補充資料
- 版本更新紀錄
- 關於作者
-
Part I:基礎篇
-
第 1 章:導論
-
為什麼需要 DI?
- 可維護性
- 寬鬆耦合
- 可測試性
- 平行開發
-
什麼是 DI?
- 入門範例—非 DI 版本
-
入門範例—DI 版本
- 提煉介面(Extract Interface)
- 控制反轉(IoC)
- 何時該用 DI?
- 本章回顧
-
為什麼需要 DI?
-
第 2 章:DI 用法與模式
-
設計模式梗概
- 小引-電器與介面
- Null Object 模式
- Decorator 模式
- Composite 模式
- Adapter 模式
- Factory 模式
-
注入方式
-
建構式注入
- 已知應用例
- 用法
- 範例程式
-
屬性注入
- 已知應用例
- 用法
- 範例程式
-
方法注入
- 已知應用例
- 用法
- 範例
-
建構式注入
-
Ambient Context 模式
- 已知應用例
- 範例程式(一)
- 範例程式(二)
- Service Locator 模式
-
過猶不及-再談建構式注入
-
半吊子注入
- 阻止相依蔓延
- 解決「半吊子注入」
-
過度注入
- 重構成參數物件
- 多載建構函式
- 重構成 Façade 模式
-
半吊子注入
- 本章回顧
-
設計模式梗概
-
第 3 章:DI 容器
-
DI 容器簡介
- 物件組合
-
自製 DI 容器
- 自製 DI 容器—2.0 版
- 現成的 DI 容器
-
物件組合
- 使用 XML
- 使用程式碼
- 自動註冊
- 自動匹配
- 深層解析
-
物件生命週期管理
- 記憶體洩漏問題
- 生命週期選項
-
攔截
- 使用 Decorator 模式實現攔截
- 本章回顧
-
DI 容器簡介
-
第 1 章:導論
-
Part II:實戰篇
-
第 4 章:DI 與 ASP.NET MVC 分層架構
-
分層架構概述
- Repository 模式
-
MVC 分層架構範例 V1-緊密耦合
- 領域模型
- 資料存取層
- 應用程式層
- 展現層
- 審視目前設計
-
MVC 分層架構範例 V2-寬鬆耦合
- 領域模型
- 資料存取層
- 應用程式層
- 展現層
-
組合物件
- 切換 Controller 工廠
- 審視目前設計
- 避免過度設計
-
MVC 分層架構範例 V3-簡化一些
- 資料存取層
- 應用程式層
- 展現層
- 審視目前設計
- 一個 HTTP 請求搭配一個 DbContext
-
ASP.NET MVC 5 的
IDependencyResolver
-
實作自訂的
IDependencyResolver
元件
-
實作自訂的
- 本章回顧
-
分層架構概述
-
第 5 章:DI 與 ASP.NET Web API
-
ASP.NET Web API 管線
- Controller 是怎樣建成的?
- 注入物件至 Web API Controller
-
抽換 IHttpControllerActivator 服務
- 純手工打造
- 使用 DI 容器:Unity
-
抽換 IDependencyResolver 服務
- IDependencyResolver 與 IDependencyScope
-
純手工 DI 範例
-
步驟 1:實作
IDependencyResolver
介面 - 步驟 2:替換預設的型別解析器
-
步驟 1:實作
- 使用 DI 容器:Unity
- 使用 DI 容器:Autofac
- 本章回顧
-
ASP.NET Web API 管線
-
第 6 章:更多 DI 實作範例
- 共用程式碼
-
DI 與 ASP.NET MVC 5
-
練習:使用 Unity
- Step 1:建立新專案
- Step 2:設定 Unity 容器
- Step 3:建立 Controller
-
練習:使用 Unity
-
DI 與 ASP.NET Web Forms
- 問題描述
- 解法
-
練習:使用 Unity
- Step 1:建立新專案
- Step 2:註冊型別
- Step 3:撰寫 HTTP Handler
- Step 4:註冊 HTTP Handler
- Step 5:撰寫測試頁面
- 練習:使用 Unity 的 BuildUp 方法
-
練習:使用 Autofac
- Step 1:建立新專案
- Step 2:註冊型別
- Step 3:撰寫 HTTP Handler
- Step 4:註冊 HTTP Handler
- Step 5:撰寫測試頁面
-
DI 與 WCF
- 問題描述
- 解法
-
練習:使用 Unity
- Step 1:建立 WCF 服務
- Step 2:撰寫自訂的 ServiceHostFactory
- Step 3:撰寫自訂的 ServiceHost
- Step 4:實作 IContractBehavior 介面
- Step 5:實作 IInstanceProvider 介面
- Step 6:設定 Unity 容器
- Step 7:修改 Web.config
- Step 8:撰寫用戶端程式
-
練習:使用 Autofac.Wcf 套件
- Step 1:建立 WCF 服務
- Step 2:撰寫自訂的 ServiceHostFactory
- Step 3:設定 Autofac 容器
- Step 4:修改 Web.config
- Step 5:撰寫用戶端程式
- 本章回顧
-
第 4 章:DI 與 ASP.NET MVC 分層架構
-
Part III:工具篇
-
第 7 章:Unity 學習手冊
-
Unity 快速入門
- Hello, Unity!
- 註冊型別對應
- 註冊既有物件
-
解析
-
解析一個物件:
Resolve
- 具名註冊與解析
-
解析多個物件:
ResolveAll
-
解析一個物件:
- 註冊與解析泛型
- 檢查註冊
-
使用組態檔來設定容器
- Unity 組態檔基本格式
- 載入組態檔設定
-
註冊與解析-進階篇
-
共用的範例程式
- 情境
- 設計
- 程式碼
-
自動註冊
- 解決重複型別對應的問題
-
AllClasses
類別 -
WithMappings
類別
-
自動匹配
- 自動匹配規則
-
手動匹配
- 循環參考問題
- 注入參數
- 注入屬性
-
延遲解析
-
使用
Lazy<T>
- 使用自動工廠
-
使用
- 注入自訂工廠
-
共用的範例程式
-
物件生命週期管理
- 預設的生命週期
-
指定生命週期
- Transient vs. Per-Resolve
- Per-Request 生命週期
- 階層式容器
- 選擇生命週期管理員
-
攔截
-
InterfaceInterceptor 範例
- Step 1:加入 Unity 攔截套件
- Step 2:實作攔截行為
- Step 3:註冊攔截行為
-
InterfaceInterceptor 範例
- 本章重點回顧
-
Unity 快速入門
-
附錄一:DI 容器實務建議
-
容器設定
- 避免對同一個組件(DLL)重複掃描兩次或更多次
- 使用不同類別來註冊不同用途的元件
- 使用非靜態類別來建立與設定 DI 容器
- 不要另外建立一個 DLL 專案來集中處理相依關係的解析
- 為個別組件加入一個初始化類別來設定相依關係
- 掃描組件時,盡量避免指定組件名稱
-
生命週期管理
- 優先使用 DI 容器來管理物件的生命週期
- 考慮使用子容器來管理 Per-Request 類型的物件
- 在適當時機呼叫容器的 Dispose 方法
-
元件設計相關建議
- 避免建立深層的巢狀物件
- 考慮使用泛型來封裝抽象概念
- 考慮使用 Adapter 或 Façade 來封裝 3rd-party 元件
- 不要一律為每個元件定義一個介面
- 對於同一層(layer)的元件,可依賴其具象型別
-
動態解析
- 盡量避免把 DI 容器直接當成 Service Locator 來使用
-
考慮使用物件工廠或
Func<T>
來處理晚期繫結
-
容器設定
-
附錄二:初探 ASP.NET 5 的內建 DI 容器
-
練習步驟
- 步驟 1:建立專案
- 步驟 2:加入必要組件
- 步驟 3:將 Web API 元件加入 ASP.NET 管線
- 步驟 4:加入 API Controller
- 步驟 5:撰寫測試用的服務類別
- 步驟 6:注入相依物件至 Controller 的建構函式
- 結語
-
練習步驟
- 版權頁
-
第 7 章:Unity 學習手冊
- 備註
關於出版社

This book is published on Leanpub by Ministep Books
Leanpub 無條件、無風險的 100% 滿意保證
從付款之後的 60 天內,只要點個兩下,你就可以完成退書並且取回先前支付的全數金額。退書是採用人工作業,因此可能需要花幾天的時間才能完成整個程序。
See full terms.
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earned$12,046,757writing, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets) and MOBI (for Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
Talking with Tech Leads
Patrick KuaA book for Tech Leads, from Tech Leads. Discover how more than 35 Tech Leads find the delicate balance between the technical and non-technical worlds. Discover the challenges a Tech Lead faces and how to overcome them. You may be surprised by the lessons they have to share.Functional Event-Driven Architecture
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way. Learn to design and develop distributed systems that scale. Identify common design patterns in such systems.
Take your functional programming skills to the next level by joining me in developing a distributed system powered by Apache Pulsar and Fs2 streams, all in Scala 3!
Machine Learning Q and AI
Sebastian Raschka, PhDHave you recently completed a machine learning or deep learning course and wondered what to learn next? With 30 questions and answers on key concepts in machine learning and AI, this book provides bite-sized bits of knowledge for your journey to becoming a machine learning expert.
Getting to Know IntelliJ IDEA
Trisha Gee and Helen ScottIf we treat our IDE as a text editor, we are doing ourselves a disservice. Using a combination of tutorials and a questions-and-answers approach, Getting to Know IntelliJ IDEA will help you find ways to use IntelliJ IDEA that enable you to work comfortably and productively as a professional developer.
The Rails 7 Way
Obie Fernandez, Lucas Dohmen, and Tom Henrik AadlandThe Rails™ 7 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. It illuminates the entire Rails 7 API, its most powerful idioms, design approaches, and libraries. Building on the previous editions, this edition has been heavily refactored and updated.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #5
1500 QUIZ COMMENTATI (3 libri)
3 Books
Tre libri dei QUIZ MMG Commentati al prezzo di DUE! I QUIZ dei concorsi ufficiali di Medicina Generale relativi agli anni: 2000-2001-2003-2012-2013-2014-2015-2016-2017-2018-2019-2020-2021 +100 inediti Raccolti in unico bundle per aiutarvi nello studio e nella preparazione al concorso. All'interno di ogni libro i quiz sono stati suddivisi per... - #6
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #8
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity... - #9
Development and Deployment of Multiplayer Online Games, Part ARCH. Architecture (Vol. I-III)
3 Books
What's the Big Idea? The idea behind this book is to summarize the body of knowledge that already exists on multiplayer games but is not available in one single place.And quite a fewof the issues discussed within this series (planned as three nine volumes ~300 pages each), while known in the industry, have not been published at all (except for...