.NET 依赖注入
.NET 依赖注入
关于本书
本书内容是关于 .NET 相依性注入(dependency injection;简称 DI)的相关议题。透过本书,您将会了解:
- 什么是 DI、它有什么优点、何时使用 DI、以及可能碰到的陷阱。
- 如何运用 DI 应付容易变动的软件需求,设计出更弹性、更好维护的程序代码。
- 与 DI 有关的设计模式。
- DI 于 .NET 应用程序中的实务应用,包括 ASP.NET MVC、ASP.NET Web API 等等。
- 如何使用 DI 容器(例如 Unity)来协助开发应用程序。
本书的范例皆以 C# 撰写,读者无须具备任何 DI 背景知识。
建议您先读完本书的试阅章节(包含本书第一章完整内容),以评估这本书是否适合你。
书籍目录
-
- 序
- 致谢
-
关于本书
- 谁适合阅读本书
- 如何阅读本书
- 书写惯例
- 需要准备的工具
- 范例程序与补充材料
- 关于作者
-
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 生命周期
- 阶层式容器
- 选择生命周期管理员
-
拦截
-
使用 Unity 容器实现拦截
- Step 1:加入 Unity 的拦截扩展包
- Step 2:实现拦截行为
- Step 3:注册拦截行为
-
使用 Unity 容器实现拦截
- 结语
-
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,307,240writing, 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.
Personal Finance
Jason AndersonThis textbook provides an in-depth analysis on personal finance that is both practical and straightforward in its approach. It has been written in such a way that the readers can gain knowledge without getting overwhelmed by the technical terms. Suitable for both beginners and advanced learners.
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.
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:
R Programming for Data Science
Roger D. PengThis book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
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.
Stats One
William FooteThe 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.
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.
Gradual Modularization for Ruby and Rails
Stephan HagemannGet yourself a new tool to manage your Rails application and your growing engineering organization! Prevent the ball-of-mud (and fix it!). Go for microservices or SOA if it makes sense not just because you don't have any other tool. Do all this through a low-overhead tool: packages. Enable better conversations to make practical changes today.
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
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... - #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
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!? - #6
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... - #7
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité... - #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... - #10
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...