这份笔记按你给的 5 个目录重新整理。第 1、4、5 章用控制台,因为要把“对象到底是谁创建的”看清楚;第 2、3 章用 WPF,带你从界面、DataContext 一路写到构造函数注入。
学习顺序不要反过来:先让最小版本跑起来,再增加一个功能,最后再看附录里的完整代码。正文里的代码是“跟着写”的版本,附录才是两个示例项目的最终文件。
先看整体地图
章节
示例项目
学完能看到什么
1. MvvmLight框架中的SimpleIoc对象使用
示例代码/SimpleIocBasics
控制台输出同一个服务实例,理解注册和获取
2. IoC容器对象项目结构的影响
示例代码/SimpleIocTour
WPF 窗口显示 ViewModel 的文字,窗口不负责创建 ViewModel
3. IoC容器中的对象依赖注入
示例代码/SimpleIocTour
构造函数需要两个服务,容器自动把两个都准备好
4. IoC概念理解与自定义IoC容器
示例代码/SimpleIocBasics
自己写出 Register 和 Resolve 两个核心动作
5. 自定义IoC容器的基本控制逻辑
示例代码/SimpleIocBasics
单例缓存、递归注入、循环依赖报错和清理
项目文件地图 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 示例代码/ ├─ SimpleIocBasics/ 控制台项目,net48 │ ├─ Program.cs 第 1、4、5 章的入口 │ ├─ Services/ │ │ ├─ IMessageService.cs │ │ ├─ MessageService.cs │ │ ├─ IClockService.cs │ │ └─ ClockService.cs │ ├─ ViewModels/ │ │ ├─ GreetingViewModel.cs │ │ └─ PropertyInjectionViewModel.cs │ └─ Ioc/ │ └─ MiniContainer.cs 自定义容器 └─ SimpleIocTour/ WPF 项目,net8.0-windows ├─ App.xaml / App.xaml.cs 组合根 ├─ Services/ │ ├─ IMessageService.cs │ ├─ MessageService.cs │ ├─ IClockService.cs │ └─ ClockService.cs ├─ ViewModels/ │ └─ MainViewModel.cs └─ Views/ ├─ MainWindow.xaml └─ MainWindow.xaml.cs
参考项目里的 App.xaml.cs 还用了 DispatcherHelper.Initialize()、ViewModelCenter 和 Messenger。那些内容属于后面的线程、消息主题。本章只保留“注册服务、创建窗口、交 DataContext”这一条主线,避免一上来就被额外概念打断。
怎么运行 先运行控制台项目:
1 dotnet run --project .\示例代码\SimpleIocBasics\SimpleIocBasics.csproj -c Release
再构建 WPF 项目:
1 dotnet build .\示例代码\SimpleIocTour\SimpleIocTour.csproj -c Release
WPF 项目构建通过后,可以用 Visual Studio 打开 SimpleIocTour.csproj 运行,也可以执行:
1 dotnet run --project .\示例代码\SimpleIocTour\SimpleIocTour.csproj -c Release
MvvmLightLibs 5.4.1.1 是较早的包,目标框架较新时可能出现 NU1701 兼容性警告。本笔记的实测结果是:控制台项目正常运行,WPF 项目构建为 0 个错误;警告不等于代码失败,但要理解它的来源。
先记住三个词
词
先这样理解
接口
只规定“要有什么方法”,不关心具体怎么做
实现
真正写方法内容的类,例如 MessageService
容器
一张登记表加一个创建入口,负责把接口和实现配对
如果你在别的 MvvmLight 笔记里看到 private set、Set(ref _x, value, nameof(X)),可以先用下面这张小表压住疑问;本笔记暂时不用属性通知,因为当前目标是看清对象创建:
写法
意思
private set
外部能读属性,只有类内部能赋值
Set(ref _x, value, nameof(X))
比较新旧值、赋值,并通知界面 X 变了
RaisePropertyChanged(nameof(Y))
手动通知界面:依赖 Y 的计算结果也要重新读
private readonly IMessageService _messageService
私有字段,通常只在构造函数里赋值一次,用来保存依赖
1. MvvmLight框架中的SimpleIoc对象使用 1. 本节目标 在一个最小控制台项目里完成三件事:注册接口、按接口取对象、观察两次取到的是不是同一个实例。
2. 一句话原理 SimpleIoc 像一个工具柜:Register 是往柜子上贴标签,GetInstance 是按标签把工具拿出来;默认情况下,拿出来后会放回原格,下次还拿同一件。
3. 要改哪里
顺序
文件
类/位置
要做什么
1
SimpleIocBasics.csproj
项目文件
引用 MvvmLightLibs
2
Services/IMessageService.cs
IMessageService 接口
规定一个返回文字的方法
3
Services/MessageService.cs
MessageService 类
真正返回文字
4
Program.cs
Program.Main
注册、获取、打印结果
4. 第一步:先让控制台能运行 本章没有 WPF 界面,先用控制台输出代替界面。打开 SimpleIocBasics/Program.cs,在 Program 类的方法区先写一个最小的 Main:
1 2 3 4 5 6 7 8 9 10 11 12 using System;namespace SimpleIocBasics { internal static class Program { private static void Main () { Console.WriteLine("程序开始" ); } } }
先运行一次,看到“程序开始”再继续。这个动作看起来简单,但很重要:先排除项目本身没建好、SDK 没装好这类问题,后面出错时才不会把问题都怪到 IoC 上。
5. 第二步:写接口、实现和最小注册 先新建 Services/IMessageService.cs。在 IMessageService 接口里写:
1 2 3 4 5 6 7 namespace SimpleIocBasics.Services { public interface IMessageService { string GetMessage () ; } }
接口只写“要有一个返回字符串的方法”,不写具体内容。再新建 Services/MessageService.cs:
1 2 3 4 5 6 7 8 9 10 namespace SimpleIocBasics.Services { public class MessageService : IMessageService { public string GetMessage () { return "你好,SimpleIoc" ; } } }
MessageService : IMessageService 表示“我来实现这个接口”。现在回到 Program.cs,把 Main 改成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 using System;using GalaSoft.MvvmLight;using SimpleIocBasics.Services;namespace SimpleIocBasics { internal static class Program { private static void Main () { var ioc = SimpleIoc.Default; ioc.Reset(); ioc.Register<IMessageService, MessageService>(); var first = ioc.GetInstance<IMessageService>(); var second = ioc.GetInstance<IMessageService>(); Console.WriteLine(first.GetMessage()); Console.WriteLine("同一个实例:" + (first == second)); } } }
6. 第三步:连接登记表和获取动作 这一段只做四步,顺序不要乱:
SimpleIoc.Default:拿到应用默认容器。
Reset():清空上一次留下的登记和缓存。它适合示例和测试开头,正式程序不要随便清空别人注册好的服务。
Register<IMessageService, MessageService>():告诉容器“别人要 IMessageService 时,创建 MessageService”。
GetInstance<IMessageService>():按接口要一个对象。
第一次 GetInstance 会创建对象并缓存;第二次再取,默认直接返回同一个对象。所以最后一行输出应该是 True。
7. 关键代码逐段看
代码
为什么这样写
SimpleIoc.Default
先拿默认容器,避免一开始就创建多个互不相干的容器
Register<IMessageService, MessageService>()
第一个泛型参数写“别人要什么”,第二个写“实际创建谁”
GetInstance<IMessageService>()
只暴露接口,调用者不需要知道 MessageService 的构造细节
first == second
用引用比较验证默认缓存是否生效
Reset()
保证本次示例从干净状态开始,避免上一次运行残留影响结果
为什么先写接口,不直接写 new MessageService()?因为一旦调用者直接 new,它就和具体类绑死了。以后换成 TimeMessageService 时,所有 new 的地方都要改;如果只依赖接口,通常只改注册那一行。
8. 运行后应该看到什么 在 SimpleIocBasics 目录运行:
1 dotnet run --project .\示例代码\SimpleIocBasics\SimpleIocBasics.csproj -c Release
本次实际运行的关键输出是:
1 2 3 SimpleIoc 单例:True SimpleIoc 注入:你好,SimpleIoc,当前时间 10:54:35 SimpleIoc 反注册:True
时间是运行时生成的,你的结果会不同;关键是 True 和问候文字能出现。
9. 对应配图
先看左边的 Program.cs,再看中间的 SimpleIoc.Default,最后看右边的“第一次请求、第二次请求”。这张图对应的就是本节 Register、GetInstance 和单例缓存的代码。
10. 跟做检查点
11. 常见错误
现象
原因
解决
找不到 SimpleIoc
没有引用 MvvmLightLibs 或没写 using GalaSoft.MvvmLight;
先检查项目引用,再检查 using
提示“未注册类型”
先 GetInstance 后 Register
把注册放在获取之前
两次对象不一样
中间调用了 Reset 或 Unregister
检查清理代码的位置
泛型顺序写反
把实现写到了第一个参数
第一个写接口,第二个写实现
12. 小练习
把 MessageService.GetMessage() 的返回值改成“你好,容器”。
再写一个 TimeMessageService,让它返回当前时间,然后把注册换成它。
在第二次获取之前调用 Unregister<IMessageService>(),观察会发生什么。
练习提示:
1 2 3 ioc.Register<IMessageService, TimeMessageService>();
13. 小结与迁移 SimpleIoc 最小用法就是“登记接口、按接口获取、需要时清理”。以后你看到某个类里直接 new 一个服务,先问自己:这个服务是不是应该由外部统一创建?如果是,就可以考虑把它交给容器。
2. IoC容器对象项目结构的影响 1. 本节目标 新建一个最小 WPF 项目,让窗口只负责显示,把“创建 ViewModel 和准备服务”的工作移到 App 这个组合根。
2. 一句话原理 把 WPF 项目想成一家餐厅:App 是店长,负责安排厨师和服务员;MainWindow 是餐桌,只负责把菜端给客人看;MainViewModel 是菜单上的内容,不负责去后厨招人。
3. 要改哪里
顺序
文件
类/位置
要做什么
1
SimpleIocTour.csproj
项目文件
建 WPF 项目并引用 MvvmLight
2
Views/MainWindow.xaml
Window 下的 Grid
放一个绑定文字的 TextBlock
3
Services/IMessageService.cs
接口
定义消息服务
4
Services/MessageService.cs
实现
返回一句问候
5
ViewModels/MainViewModel.cs
构造函数
接收 IMessageService
6
App.xaml
Application 标签
删除 StartupUri
7
App.xaml.cs
App.OnStartup
注册服务、创建窗口、交 DataContext
4. 第一步:写最小界面 新建 WPF 项目 SimpleIocTour,把窗口放到 Views/MainWindow.xaml。先只写一个标题和一个绑定文字的 TextBlock:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <Window x:Class ="SimpleIocTour.Views.MainWindow" xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" Title ="SimpleIoc Tour" Height ="300" Width ="600" WindowStartupLocation ="CenterScreen" > <Grid Background ="#F4F7FB" > <StackPanel Margin ="32" > <TextBlock Text ="SimpleIoc 已经接管对象创建" FontSize ="26" FontWeight ="Bold" /> <TextBlock Margin ="0,24,0,0" Text ="{Binding Message}" FontSize ="22" Foreground ="#2563EB" /> </StackPanel > </Grid > </Window >
这里第一次出现 {Binding Message},先记住一句话:它会让 WPF 去当前 DataContext 里找名为 Message 的属性。现在 DataContext 还没设置,所以运行时暂时看不到文字,这是正常的。
5. 第二步:写最小 ViewModel 和服务 先新建 Services/IMessageService.cs 和 Services/MessageService.cs,内容与第 1 章相同,只是命名空间改成 SimpleIocTour.Services。然后新建 ViewModels/MainViewModel.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 using SimpleIocTour.Services;namespace SimpleIocTour.ViewModels { public class MainViewModel { private readonly IMessageService _messageService; public MainViewModel (IMessageService messageService ) { _messageService = messageService; } public string Message { get { return _messageService.GetMessage(); } } } }
注意:这里没有 new MessageService()。构造函数只写“我需要一个 IMessageService”,具体是哪一个实现,交给外面决定。
6. 第三步:在 App 中注册并连接窗口 打开 App.xaml,删除 StartupUri="MainWindow.xaml"。如果不删,WPF 会自动创建一个窗口,而 OnStartup 里又手动创建一个,就会看到两个窗口。
然后在 App.xaml.cs 的 App 类里写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System.Windows;using GalaSoft.MvvmLight;using SimpleIocTour.Services;using SimpleIocTour.ViewModels;using SimpleIocTour.Views;namespace SimpleIocTour { public partial class App : Application { protected override void OnStartup (StartupEventArgs e ) { base .OnStartup(e); var ioc = SimpleIoc.Default; ioc.Reset(); ioc.Register<IMessageService, MessageService>(); ioc.Register<MainViewModel>(); var window = new MainWindow(); window.DataContext = ioc.GetInstance<MainViewModel>(); window.Show(); } } }
base.OnStartup(e) 的意思是“先让 WPF 完成它原本的启动流程,我再加自己的代码”。这里没有 DispatcherHelper,也没有 Messenger,因为本章不需要它们。
最后确认 Views/MainWindow.xaml.cs 只保留:
1 2 3 4 5 6 7 8 9 10 11 12 using System.Windows;namespace SimpleIocTour.Views { public partial class MainWindow : Window { public MainWindow () { InitializeComponent(); } } }
7. 关键代码逐段看
代码
意思
DataContext
绑定起点;窗口里的控件会沿着它找属性
{Binding Message}
去当前 DataContext 里找 Message
ioc.Register<MainViewModel>()
告诉容器:这个类型也可以由你创建
GetInstance<MainViewModel>()
容器发现构造函数要 IMessageService,先创建服务,再创建 ViewModel
window.DataContext = ...
把准备好的 ViewModel 交给窗口
DataContext 会沿着可视树向下继承,所以只要窗口的 DataContext 设置好了,窗口里面的 TextBlock 就能直接写 {Binding Message},不需要每个控件再单独赋值。
为什么不在 MainWindow.xaml.cs 里写 this.DataContext = new MainViewModel(new MessageService());?小练习可以这样做,因为它最直观;但项目一大,窗口就会知道太多服务的创建细节。把创建集中到 App,窗口只认 DataContext,以后换实现、加日志、加配置时,不需要改窗口。
8. 运行后应该看到什么 如果按正文的最小版本做,运行后应该只出现一个窗口,窗口里有标题和一句“你好,SimpleIoc”。窗口代码里没有 new MainViewModel(),但 {Binding Message} 仍然能显示文字,因为 App 已经把 ViewModel 放进了 DataContext。
结果如图:
9. 对应配图
先看左边的目录树,确认 Services、ViewModels、Views 各自放什么;再看右边的箭头:App.OnStartup 先找 SimpleIoc,SimpleIoc 创建 MainViewModel,最后 MainWindow 只负责显示。
10. 跟做检查点
11. 常见错误
现象
原因
解决
打开两个窗口
还留着 StartupUri
删除 StartupUri,只保留手动创建
窗口里没有文字
没有设置 DataContext
在 App.OnStartup 里给 window.DataContext 赋值
提示找不到 MainViewModel
没有注册 ViewModel
加 ioc.Register<MainViewModel>()
提示找不到 IMessageService
没有注册接口
在获取 ViewModel 之前注册服务
XAML 报“找不到类型”
x:Class 或命名空间不一致
对照文件路径和 namespace 检查
12. 小练习
把 MessageService.GetMessage() 的返回值改成你自己的名字。
在窗口里再加一个 TextBlock,显示一句固定说明文字。
故意把 window.DataContext 那一行注释掉,观察窗口是否还能显示绑定内容。
13. 小结与迁移 IoC 对项目结构最大的影响,是把“谁创建对象”从各个窗口和 ViewModel 里搬到了 App 这样的组合根。以后你新建页面时,可以先问:这个页面的 ViewModel 应该由谁创建?如果答案是“统一入口”,就把注册放到组合根,把 DataContext 交给页面。
3. IoC容器中的对象依赖注入 1. 本节目标 让 MainViewModel 的构造函数同时需要 IMessageService 和 IClockService,观察容器如何先把两个服务准备好,再把它们传进去。
2. 一句话原理 构造函数注入像点套餐:你告诉服务员“我要主食和饮料”,后厨先把两样都准备好,再一起端上来;MainViewModel 不需要自己进厨房做任何一样。
3. 要改哪里
顺序
文件
类/位置
要做什么
1
Services/IClockService.cs
新接口
规定返回时间的方法
2
Services/ClockService.cs
新实现
返回当前时间
3
ViewModels/MainViewModel.cs
构造函数
增加 IClockService 参数
4
Views/MainWindow.xaml
StackPanel
增加时间文字
5
App.xaml.cs
App.OnStartup
注册 IClockService
4. 第一步:先改界面,给时间留位置 打开 Views/MainWindow.xaml,在原来的消息 TextBlock 下面增加两行:
1 2 3 4 5 6 7 8 <TextBlock Margin ="0,20,0,0" Text ="当前时间" FontSize ="14" Foreground ="#6B7280" /> <TextBlock Text ="{Binding Time}" FontSize ="24" FontWeight ="SemiBold" Foreground ="#111827" />
这里仍然只写绑定,不写 DateTime.Now。界面不应该负责取时间,时间来自 ViewModel 后面的服务。
5. 第二步:增加时间服务并修改 ViewModel 新建 Services/IClockService.cs:
1 2 3 4 5 6 7 namespace SimpleIocTour.Services { public interface IClockService { string GetNow () ; } }
再新建 Services/ClockService.cs:
1 2 3 4 5 6 7 8 9 10 11 12 using System;namespace SimpleIocTour.Services { public class ClockService : IClockService { public string GetNow () { return DateTime.Now.ToString("HH:mm:ss" ); } } }
然后打开 ViewModels/MainViewModel.cs,把构造函数改成两个参数,并增加 Time 属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 using SimpleIocTour.Services;namespace SimpleIocTour.ViewModels { public class MainViewModel { private readonly IMessageService _messageService; private readonly IClockService _clockService; public MainViewModel ( IMessageService messageService, IClockService clockService ) { _messageService = messageService; _clockService = clockService; } public string Message { get { return _messageService.GetMessage(); } } public string Time { get { return _clockService.GetNow(); } } } }
6. 第三步:在 App 中补注册 打开 App.xaml.cs,在 App.OnStartup 的注册区增加一行:
1 2 3 ioc.Register<IMessageService, MessageService>(); ioc.Register<IClockService, ClockService>(); ioc.Register<MainViewModel>();
注册顺序不是重点,重点是:在 GetInstance<MainViewModel>() 之前,构造函数需要的两个接口都已经登记好。容器会先解析 IMessageService 和 IClockService,再调用 MainViewModel 的构造函数。
7. 关键代码逐段看
代码
意思
MainViewModel(IMessageService, IClockService)
ViewModel 声明自己需要两个能力
Register<IMessageService, MessageService>()
告诉容器“消息能力用这个实现”
Register<IClockService, ClockService>()
告诉容器“时间能力用这个实现”
GetInstance<MainViewModel>()
容器先准备参数,再创建 ViewModel
Time 属性
界面通过绑定读时间,不直接调用 DateTime.Now
参考项目用 IDataAccess、SqlServerDA、MySqlDA 演示数据库切换;这里改用消息和时间服务,原理相同,但不需要安装数据库。你可以把 MessageService 换成另一个实现,只要新类仍然实现 IMessageService,MainViewModel 不用改。
8. 运行后应该看到什么 窗口里会显示问候文字和当前时间,例如:
1 2 你好,SimpleIoc 已经接管对象创建。 10:54:35
时间每次运行都可能不同。关键是:MainWindow.xaml.cs 没有创建任何服务,MainViewModel 也没有 new ClockService()。
9. 对应配图
先看最上面的 MainViewModel 构造函数,它像一张订单;再看下面两条箭头,分别把 IMessageService 和 IClockService 送进构造函数;最后看底部的“创建顺序”。
10. 跟做检查点
11. 常见错误
现象
原因
解决
提示 IClockService 未注册
只注册了消息服务
补 Register<IClockService, ClockService>()
提示没有无参构造函数
容器找不到参数对应的登记
检查两个接口是否都注册
时间不显示
XAML 绑定的属性名写错
确认 ViewModel 里叫 Time,XAML 也写 Time
改了实现但窗口没变化
注册的仍然是旧实现
检查 Register 的第二个泛型参数
12. 小练习
写一个 EnglishMessageService,让它返回英文问候,然后在 App 里替换注册。
写一个 FixedClockService,让 GetNow() 永远返回 "12:00:00",方便测试。
思考:如果 MessageService 自己也需要一个 IClockService,容器还能自动处理吗?
13. 小结与迁移 构造函数注入的核心不是“容器很聪明”,而是“类把需要的东西写在构造函数上,容器按这个清单去准备”。以后写 ViewModel、Service、Repository,都可以先列清单:我真正需要哪些接口?这些接口在组合根注册了吗?
4. IoC概念理解与自定义IoC容器 1. 本节目标 不借助 SimpleIoc,自己写一个只有“登记”和“解析”的最小容器 MiniContainer,并用它取到一个消息服务。
2. 一句话原理 最小容器就是一张字典:Register 把“接口类型”对应到“创建函数”,Resolve 按类型找到函数并执行。控制反转的意思是:创建对象的权力从调用者手里,转到了这张字典手里。
3. 要改哪里
顺序
文件
类/位置
要做什么
1
Ioc/MiniContainer.cs
字段区
建一个 Dictionary<Type, Func<object>>
2
Ioc/MiniContainer.cs
方法区
写 Register 和 Resolve
3
Program.cs
Main
注册接口并解析
4. 第一步:写最小容器 新建 Ioc/MiniContainer.cs,先只写最核心的两个动作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 using System;using System.Collections.Generic;namespace SimpleIocBasics.Ioc { public class MiniContainer { private readonly Dictionary<Type, Func<object >> _factories = new Dictionary<Type, Func<object >>(); public void Register <TInterface , TImplementation >() where TImplementation : TInterface { _factories[typeof (TInterface)] = () => Activator.CreateInstance<TImplementation>(); } public T Resolve <T >() { return (T)_factories[typeof (T)].Invoke(); } } }
这个版本故意很小,只解决“无参构造函数”的情况。where TImplementation : TInterface 是泛型约束,意思是“第二个类型必须能当成第一个类型使用”,所以不能把两个毫不相干的类型乱配。
5. 第二步:用最小容器取对象 在 Program.cs 的 Main 里先只测试这一小段:
1 2 3 4 5 var container = new MiniContainer(); container.Register<IMessageService, MessageService>();var service = container.Resolve<IMessageService>(); Console.WriteLine(service.GetMessage());
运行后应该输出:
这里没有 new MessageService()。Register 只是登记创建方法,Resolve 才真正执行 Activator.CreateInstance<MessageService>()。
6. 第三步:理解“控制反转” 传统写法是调用者自己创建依赖:
1 2 var service = new MessageService();var viewModel = new GreetingViewModel(service);
创建权在调用者手里。用容器后,调用者只说要什么:
1 var viewModel = container.Resolve<GreetingViewModel>();
创建权在容器手里。这个“把创建权交出去”的动作,就是控制反转。注意:本章的 MiniContainer 还不能创建 GreetingViewModel,因为 GreetingViewModel 的构造函数需要参数;第 5 章会补上。
7. 关键代码逐段看
代码
意思
Dictionary<Type, Func<object>>
类型到“创建函数”的登记表
typeof(TInterface)
用接口类型作为字典的 key
Activator.CreateInstance<TImplementation>()
让反射帮你调用无参构造函数
_factories[typeof(T)].Invoke()
找到创建函数并执行
(T)
把创建出来的对象转成调用者要的接口
为什么用 Func<object>,不直接存对象?因为注册时还不应该创建对象;等到 Resolve 时才创建,才能控制创建时机,也方便以后加入缓存。
8. 运行后应该看到什么 控制台输出 你好,SimpleIoc。这时你还没有用 SimpleIoc,但已经完成了 IoC 的两个核心动作:登记和解析。
9. 对应配图
先看左边的 _factories,它负责“怎么创建”;再看右边的四步流程,理解 Resolve 不是魔法,而是查字典、执行函数、返回结果。
10. 跟做检查点
11. 常见错误
现象
原因
解决
找不到 Type 或 Func
没写 using System;
补上命名空间
提示 key 不存在
没先注册就 Resolve
先 Register,再解析
提示没有无参构造函数
Activator.CreateInstance 的限制
第 5 章改成构造函数注入
泛型顺序写反
接口和实现写反
第一个接口,第二个实现
12. 小练习
增加一个 IClockService 和 ClockService,用最小容器解析它。
故意不注册 IMessageService,观察异常。
思考:为什么 Resolve<T>() 需要把结果强制转换成 T?
13. 小结与迁移 IoC 不是框架专属名词。只要把“创建对象”的职责从调用者手里拿走,交给一个统一入口,就已经用上了 IoC。MiniContainer 很小,但已经具备“登记”和“解析”两个核心动作。
5. 自定义IoC容器的基本控制逻辑 1. 本节目标 把第 4 章的 MiniContainer 升级成能缓存单例、递归处理构造函数参数、检测循环依赖、清理登记和缓存的版本,并观察真实输出。
2. 一句话原理 一个能用的容器至少要有三块:登记表决定“怎么建”,缓存决定“建过没有”,创建逻辑决定“参数从哪里来”。再加一个“出错时能说清楚”的检查,就不会出现悄悄塞 null 的情况。
3. 要改哪里
顺序
文件
类/位置
要做什么
1
Ioc/MiniContainer.cs
字段区
增加 _singletons 和 _creating
2
Ioc/MiniContainer.cs
Resolve
先查缓存,再查登记,再创建
3
Ioc/MiniContainer.cs
CreateInstance
读取构造函数参数并递归解析
4
Ioc/MiniContainer.cs
方法区
增加 Unregister、Reset、InjectProperties
5
Program.cs
Main
验证单例、注入、清理和属性注入
4. 第一步:增加单例缓存 在 MiniContainer 的字段区增加:
1 2 3 4 5 private readonly Dictionary<Type, object > _singletons = new Dictionary<Type, object >();private readonly HashSet<Type> _creating = new HashSet<Type>();
在 Resolve(Type type) 的开头先查缓存:
1 2 3 4 5 object existing;if (_singletons.TryGetValue(type, out existing)) { return existing; }
创建成功后,再把对象放进去:
1 2 3 var instance = factory(); _singletons[type] = instance;return instance;
这样第二次解析同一个类型时,就不会再次执行创建函数。
5. 第二步:加入构造函数注入和循环检查 在 MiniContainer 中加入 CreateInstance。在 Resolve(Type type) 里,找到 factory 之后,把创建部分改成下面这样,用它记录“正在创建”的类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 if (_creating.Contains(type)) { throw new InvalidOperationException( "检测到循环依赖:" + type.Name); } _creating.Add(type);try { var instance = factory(); _singletons[type] = instance; return instance; }finally { _creating.Remove(type); }
_creating 只在“正在创建”的这段时间里保存类型。创建完成后无论成功还是失败,finally 都会把它移除,所以不会把正常类型误判成循环依赖。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 private object CreateInstance (Type type ) { var constructor = type.GetConstructors() .OrderByDescending(item => item.GetParameters().Length) .First(); var parameters = constructor.GetParameters() .Select(parameter => { if (!IsRegistered(parameter.ParameterType)) { throw new InvalidOperationException( "类型 " + type.Name + " 需要 " + parameter.ParameterType.Name + ",但它还没有注册。" ); } return Resolve(parameter.ParameterType); }) .ToArray(); return constructor.Invoke(parameters); }
这段代码做四步:
找到构造函数。
取出参数列表。
对每个参数调用 Resolve,参数自己还有依赖就继续递归。
用 Invoke 把参数传进去,创建对象。
如果没有注册参数类型,这里直接抛出异常,不再使用 objects.Add(null) 那种“悄悄传空值”的写法。空值会让错误延迟到业务代码里才爆出来,排查更困难。
6. 第三步:验证单例、注入和清理 在 Program.cs 里写一个最小验证:
1 2 3 4 5 6 7 8 9 10 var container = new MiniContainer(); container.Register<IMessageService, MessageService>(); container.Register<IClockService, ClockService>(); container.Register<GreetingViewModel, GreetingViewModel>();var first = container.Resolve<GreetingViewModel>();var second = container.Resolve<GreetingViewModel>(); Console.WriteLine("单例:" + (first == second)); Console.WriteLine("注入:" + first.Text);
GreetingViewModel 的构造函数需要 IMessageService 和 IClockService,容器会先解析两个参数,再创建 GreetingViewModel。所以这里的“递归”不是玄学,而是 Resolve 在参数上又调用了一次自己。
6.1 补上清理和属性注入 在 MiniContainer 的方法区继续加入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public bool IsRegistered <T >() { return _factories.ContainsKey(typeof (T)); }public void Unregister <T >() { _factories.Remove(typeof (T)); _singletons.Remove(typeof (T)); }public void Reset () { _factories.Clear(); _singletons.Clear(); _creating.Clear(); }
如果要做属性注入,再增加一个 InjectProperties 方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public void InjectProperties (object instance ) { var properties = instance.GetType() .GetProperties() .Where(property => property.CanWrite && IsRegistered(property.PropertyType)); foreach (var property in properties) { property.SetValue( instance, Resolve(property.PropertyType), null ); } }
属性注入是可选的扩展,不是构造函数注入的替代品。它适合“可选依赖”或“稍后补充”的属性;如果对象离开某个依赖就无法工作,优先用构造函数注入。
7. 关键代码逐段看
代码
意思
_singletons
已经创建过的对象,按类型缓存
_creating
当前正在创建的类型,用来发现循环依赖
TryGetValue
先看有没有缓存或登记,避免直接索引抛异常
GetParameters()
拿到构造函数需要哪些参数
Select(parameter => Resolve(...))
对每个参数继续解析
constructor.Invoke(parameters)
用准备好的参数创建对象
Unregister<T>()
移除登记,同时移除它的缓存
Reset()
清空全部登记、缓存和创建状态
参考项目的 ZhaoxiIoc 是教学版,能帮助理解思路,但直接扩展时要注意几个点:
参考项目写法
容易出现的现象
本笔记的推荐写法
_instenceDic.Add(...)
重复注册会抛异常
用索引器赋值,后注册覆盖前一个
Resolve<T> 只查 _instenceDic
_objectsDic 实际没有参与解析
只保留一张创建登记表
缺依赖时 objects.Add(null)
错误延迟到业务代码才出现
未注册就直接抛出明确异常
只处理构造函数的第一层参数
多层依赖不能稳定创建
Resolve 递归处理参数
App 和 ViewModelCenter 都注册
重复注册、职责不清
只保留一个组合根
8. 运行后应该看到什么 本次实际运行 SimpleIocBasics 的输出是:
1 2 3 4 5 6 7 8 9 SimpleIoc 单例:True SimpleIoc 注入:你好,SimpleIoc,当前时间 10:54:35 SimpleIoc 反注册:True 自定义容器单例:True 自定义容器注入:你好,SimpleIoc,当前时间 10:54:35 自定义容器反注册:True 自定义容器重置:True 自定义容器属性注入:你好,SimpleIoc 全部通过
时间会随运行时刻变化。True 说明单例缓存生效;自定义容器注入 说明构造函数参数被正确解析;最后一行说明属性注入也能工作。
9. 对应配图
先看左上角的“缓存命中”,再看右上角的“未注册类型”,然后看下面的“循环依赖”和“清理与重置”。这四块就是第 5 章要补的控制逻辑。
10. 跟做检查点
11. 常见错误
现象
原因
解决
找不到 OrderByDescending
没写 using System.Linq;
补上 LINQ 命名空间
一直递归到崩溃
A 依赖 B,B 又依赖 A
检查循环依赖,_creating 会报错
提示“类型需要 X,但它还没有注册”
参数类型没登记
在 Resolve 前注册参数类型
每次都是同一个对象
单例缓存生效
这是预期行为;需要新对象时改生命周期策略
重复注册报错
使用了 Dictionary.Add
用索引器赋值,明确覆盖规则
12. 小练习
给 MiniContainer 增加 Register<TInterface>(Func<TInterface> factory),用工厂创建对象。
写一个 FakeClockService,让时间固定,方便对比输出。
故意让两个类互相依赖,观察循环依赖异常的文字。
13. 小结与迁移 自定义容器的基本控制逻辑就是:登记、解析、缓存、递归注入、清理和报错。SimpleIoc 比 MiniContainer 多了键值注册、工厂、生命周期等能力,但核心思想相同。以后看到任何 IoC 容器,都可以先找这五样东西。
运行验证 本次已经实际执行过控制台项目,关键输出见第 5 章第 8 节;WPF 项目已经用下面的命令构建成功:
1 dotnet build .\示例代码\SimpleIocTour\SimpleIocTour.csproj -c Release
构建结果是 0 个错误。由于 MvvmLightLibs 5.4.1.1 的目标框架较旧,构建会提示 NU1701 兼容性警告;这表示包不是为 net8.0-windows 原生编译的,但本次项目仍能构建。若你的课程环境要求 net7.0-windows 或 net48,按你项目实际版本调整 TargetFramework,不要盲目照抄框架版本。
WPF 运行时的预期界面是:一个窗口,标题为 SimpleIoc Tour,显示问候文字和当前时间。窗口的 MainWindow.xaml.cs 只调用 InitializeComponent(),对象创建发生在 App.OnStartup。
最终检查清单
附录:完整示例代码 正文为了讲清楚每一步,部分类只展示了最小片段;下面是两个示例项目的实际文件,可以直接对照。WPF 项目的最终版本比第 2 章的最小版本多了 IClockService,这是第 3 章逐步加上的结果。
SimpleIocBasics
项目文件:SimpleIocBasics.csproj
1 2 3 4 5 6 7 8 9 10 11 12 <Project Sdk ="Microsoft.NET.Sdk" > <PropertyGroup > <OutputType > Exe</OutputType > <TargetFramework > net48</TargetFramework > <LangVersion > 7.3</LangVersion > <Nullable > disable</Nullable > </PropertyGroup > <ItemGroup > <PackageReference Include ="MvvmLightLibs" Version ="5.4.1.1" /> </ItemGroup > </Project >
程序入口:Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 using System;using GalaSoft.MvvmLight.Ioc;using SimpleIocBasics.Ioc;using SimpleIocBasics.Services;using SimpleIocBasics.ViewModels;namespace SimpleIocBasics { internal static class Program { private static void Main () { RunSimpleIocDemo(); RunMiniContainerDemo(); Console.WriteLine("全部通过" ); } private static void RunSimpleIocDemo () { var ioc = SimpleIoc.Default; ioc.Reset(); ioc.Register<IMessageService, MessageService>(); ioc.Register<IClockService, ClockService>(); ioc.Register<GreetingViewModel>(); var first = ioc.GetInstance<IMessageService>(); var second = ioc.GetInstance<IMessageService>(); var viewModel = ioc.GetInstance<GreetingViewModel>(); Console.WriteLine("SimpleIoc 单例:" + (first == second)); Console.WriteLine("SimpleIoc 注入:" + viewModel.Text); ioc.Unregister<IMessageService>(); Console.WriteLine( "SimpleIoc 反注册:" + !ioc.IsRegistered<IMessageService>()); } private static void RunMiniContainerDemo () { var container = new MiniContainer(); container.Register<IMessageService, MessageService>(); container.Register<IClockService, ClockService>(); container.Register<GreetingViewModel, GreetingViewModel>(); var first = container.Resolve<GreetingViewModel>(); var second = container.Resolve<GreetingViewModel>(); Console.WriteLine("自定义容器单例:" + (first == second)); Console.WriteLine("自定义容器注入:" + first.Text); container.Unregister<IMessageService>(); Console.WriteLine( "自定义容器反注册:" + !container.IsRegistered<IMessageService>()); container.Reset(); Console.WriteLine( "自定义容器重置:" + !container.IsRegistered<GreetingViewModel>()); container.Register<IMessageService, MessageService>(); container.Register<PropertyInjectionViewModel, PropertyInjectionViewModel>(); var propertyViewModel = container.Resolve<PropertyInjectionViewModel>(); container.InjectProperties(propertyViewModel); Console.WriteLine( "自定义容器属性注入:" + propertyViewModel.Text); } } }
消息接口:Services/IMessageService.cs
1 2 3 4 5 6 7 namespace SimpleIocBasics.Services { public interface IMessageService { string GetMessage () ; } }
消息实现:Services/MessageService.cs
1 2 3 4 5 6 7 8 9 10 namespace SimpleIocBasics.Services { public class MessageService : IMessageService { public string GetMessage () { return "你好,SimpleIoc" ; } } }
时间接口:Services/IClockService.cs
1 2 3 4 5 6 7 namespace SimpleIocBasics.Services { public interface IClockService { string GetNow () ; } }
时间实现:Services/ClockService.cs
1 2 3 4 5 6 7 8 9 10 11 12 using System;namespace SimpleIocBasics.Services { public class ClockService : IClockService { public string GetNow () { return DateTime.Now.ToString("HH:mm:ss" ); } } }
问候 ViewModel:ViewModels/GreetingViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 using SimpleIocBasics.Services;namespace SimpleIocBasics.ViewModels { public class GreetingViewModel { private readonly IMessageService _messageService; private readonly IClockService _clockService; public GreetingViewModel ( IMessageService messageService, IClockService clockService ) { _messageService = messageService; _clockService = clockService; } public string Text { get { return _messageService.GetMessage() + ",当前时间 " + _clockService.GetNow(); } } } }
属性注入 ViewModel:ViewModels/PropertyInjectionViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 using SimpleIocBasics.Services;namespace SimpleIocBasics.ViewModels { public class PropertyInjectionViewModel { public IMessageService MessageService { get ; set ; } public string Text { get { if (MessageService == null ) { return "属性还没有注入" ; } return MessageService.GetMessage(); } } } }
自定义容器:Ioc/MiniContainer.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 using System;using System.Collections.Generic;using System.Linq;namespace SimpleIocBasics.Ioc { public class MiniContainer { private readonly Dictionary<Type, Func<object >> _factories = new Dictionary<Type, Func<object >>(); private readonly Dictionary<Type, object > _singletons = new Dictionary<Type, object >(); private readonly HashSet<Type> _creating = new HashSet<Type>(); public void Register <TInterface , TImplementation >() where TImplementation : TInterface { _factories[typeof (TInterface)] = () => CreateInstance(typeof (TImplementation)); } public void Register <TInterface >(Func<TInterface> factory ) { _factories[typeof (TInterface)] = () => factory(); } public T Resolve <T >() { return (T)Resolve(typeof (T)); } public bool IsRegistered <T >() { return _factories.ContainsKey(typeof (T)); } public void Unregister <T >() { _factories.Remove(typeof (T)); _singletons.Remove(typeof (T)); } public void Reset () { _factories.Clear(); _singletons.Clear(); _creating.Clear(); } public void InjectProperties (object instance ) { var properties = instance.GetType() .GetProperties() .Where(property => property.CanWrite && IsRegistered(property.PropertyType)); foreach (var property in properties) { property.SetValue( instance, Resolve(property.PropertyType), null ); } } private object Resolve (Type type ) { object existing; if (_singletons.TryGetValue(type, out existing)) { return existing; } if (_creating.Contains(type)) { throw new InvalidOperationException( "检测到循环依赖:" + type.Name); } Func<object > factory; if (!_factories.TryGetValue(type, out factory)) { throw new InvalidOperationException( "未注册类型:" + type.FullName); } _creating.Add(type); try { var instance = factory(); _singletons[type] = instance; return instance; } finally { _creating.Remove(type); } } private bool IsRegistered (Type type ) { return _factories.ContainsKey(type); } private object CreateInstance (Type type ) { var constructors = type.GetConstructors(); if (constructors.Length == 0 ) { throw new InvalidOperationException( "类型没有公开构造函数:" + type.FullName); } var constructor = constructors .OrderByDescending(item => item.GetParameters().Length) .First(); var parameters = constructor.GetParameters() .Select(parameter => { if (!IsRegistered(parameter.ParameterType)) { throw new InvalidOperationException( "类型 " + type.Name + " 需要 " + parameter.ParameterType.Name + ",但它还没有注册。" ); } return Resolve(parameter.ParameterType); }) .ToArray(); return constructor.Invoke(parameters); } } }
SimpleIocTour
WPF 项目文件:SimpleIocTour.csproj
1 2 3 4 5 6 7 8 9 10 11 12 <Project Sdk ="Microsoft.NET.Sdk" > <PropertyGroup > <OutputType > WinExe</OutputType > <TargetFramework > net8.0-windows</TargetFramework > <Nullable > disable</Nullable > <UseWPF > true</UseWPF > </PropertyGroup > <ItemGroup > <PackageReference Include ="MvvmLightLibs" Version ="5.4.1.1" /> </ItemGroup > </Project >
WPF 应用:App.xaml
1 2 3 4 5 6 <Application x:Class ="SimpleIocTour.App" xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" > <Application.Resources > </Application.Resources > </Application >
WPF 启动入口:App.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 using System.Windows;using GalaSoft.MvvmLight.Ioc;using SimpleIocTour.Services;using SimpleIocTour.ViewModels;using SimpleIocTour.Views;namespace SimpleIocTour { public partial class App : Application { protected override void OnStartup (StartupEventArgs e ) { base .OnStartup(e); var ioc = SimpleIoc.Default; ioc.Reset(); ioc.Register<IMessageService, MessageService>(); ioc.Register<IClockService, ClockService>(); ioc.Register<MainViewModel>(); var window = new MainWindow(); window.DataContext = ioc.GetInstance<MainViewModel>(); window.Show(); } } }
消息接口:Services/IMessageService.cs
1 2 3 4 5 6 7 namespace SimpleIocTour.Services { public interface IMessageService { string GetMessage () ; } }
消息实现:Services/MessageService.cs
1 2 3 4 5 6 7 8 9 10 namespace SimpleIocTour.Services { public class MessageService : IMessageService { public string GetMessage () { return "你好,SimpleIoc 已经接管对象创建。" ; } } }
时间接口:Services/IClockService.cs
1 2 3 4 5 6 7 namespace SimpleIocTour.Services { public interface IClockService { string GetNow () ; } }
时间实现:Services/ClockService.cs
1 2 3 4 5 6 7 8 9 10 11 12 using System;namespace SimpleIocTour.Services { public class ClockService : IClockService { public string GetNow () { return DateTime.Now.ToString("HH:mm:ss" ); } } }
主 ViewModel:ViewModels/MainViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 using SimpleIocTour.Services;namespace SimpleIocTour.ViewModels { public class MainViewModel { private readonly IMessageService _messageService; private readonly IClockService _clockService; public MainViewModel ( IMessageService messageService, IClockService clockService ) { _messageService = messageService; _clockService = clockService; } public string Message { get { return _messageService.GetMessage(); } } public string Time { get { return _clockService.GetNow(); } } } }
主窗口:Views/MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <Window x:Class ="SimpleIocTour.Views.MainWindow" xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" Title ="SimpleIoc Tour" Height ="340" Width ="640" WindowStartupLocation ="CenterScreen" > <Grid Background ="#F4F7FB" > <Border Margin ="24" Padding ="28" Background ="White" CornerRadius ="12" > <StackPanel > <TextBlock Text ="SimpleIoc 已经接管对象创建" FontSize ="26" FontWeight ="Bold" Foreground ="#1F2937" /> <TextBlock Margin ="0,20,0,0" Text ="{Binding Message}" FontSize ="20" Foreground ="#2563EB" /> <TextBlock Margin ="0,18,0,0" Text ="当前时间" FontSize ="14" Foreground ="#6B7280" /> <TextBlock Text ="{Binding Time}" FontSize ="24" FontWeight ="SemiBold" Foreground ="#111827" /> <TextBlock Margin ="0,24,0,0" Text ="MainWindow 只负责显示,MainViewModel 由 App 交给它。" FontSize ="14" Foreground ="#6B7280" /> </StackPanel > </Border > </Grid > </Window >
主窗口后台:Views/MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 using System.Windows;namespace SimpleIocTour.Views { public partial class MainWindow : Window { public MainWindow () { InitializeComponent(); } } }