docs(context-get): 更新上下文注入生成器文档

- 在多个示例中添加 __InjectContextBindings_Generated() 调用
- 重写推荐调用时机与模式章节,强调在生命周期入口统一调用
- 添加 Godot 节点和测试场景的具体使用模式
- 重构诊断信息表格,整合 Priority 和 Context Get 相关诊断
- 更新 FAQ 部分关于构造函数使用的建议
This commit is contained in:
GeWuYou 2026-03-29 20:23:45 +08:00
parent 159578ab90
commit c9423702a2
2 changed files with 99 additions and 329 deletions

View File

@ -67,7 +67,9 @@ public partial class PlayerController
public void Initialize()
{
// 字段已自动注入,可直接使用
// 在首次使用注入字段前,先完成绑定
__InjectContextBindings_Generated();
_combatSystem.Attack(_playerModel);
}
}
@ -91,6 +93,8 @@ public partial class StrategyManager
public void ProcessAll()
{
__InjectContextBindings_Generated();
foreach (var system in _gameSystems)
{
system.Initialize();
@ -154,9 +158,20 @@ partial class PlayerController
}
```
### 调用时机
### 推荐调用时机与模式
注入方法需要在适当的时机手动调用:
生成器只负责生成 `__InjectContextBindings_Generated()` 方法,不会自动织入构造函数或生命周期回调。推荐统一遵循下面两条规则:
- 在上下文已经可用之后调用,例如 `Initialize()``OnEnter()`、Godot 的 `_Ready()` 或测试初始化阶段。
- 在首次读取任一注入字段之前调用。不要在构造函数体中假设这些字段已经可用。
推荐把调用集中放在单一的生命周期入口,而不是分散到构造函数、`_Ready()``Initialize()`
等多个位置。这样更容易保证字段只在“上下文已准备好且尚未被读取”时完成注入。
由于该方法是生成的私有成员,类外代码(包括测试)应复用类内部公开的生命周期入口,而不是直接调用生成方法。
#### 普通类型推荐模式
对普通控制器、服务协调器或策略管理器,优先在显式初始化方法开头调用:
```csharp
[ContextAware]
@ -166,20 +181,57 @@ public partial class GameController
private IPlayerModel _player = null!;
private ICombatSystem _combat = null!;
public GameController()
{
// 在构造函数后调用注入方法
__InjectContextBindings_Generated();
}
public void Initialize()
{
// 此时字段已注入,可以安全使用
__InjectContextBindings_Generated();
_combat.Initialize(_player);
}
}
```
#### Godot 节点推荐模式
`Node` 类型,优先在 `_Ready()` 开头调用,再使用注入字段:
```csharp
[ContextAware]
[GetAll]
public partial class PlayerNode : Node
{
private IPlayerModel _model = null!;
private IMovementSystem _movement = null!;
public override void _Ready()
{
__InjectContextBindings_Generated();
_movement.Initialize(_model);
}
}
```
#### 测试与手动装配模式
先配置上下文提供者,再调用与生产代码一致的公开入口,让入口内部完成注入:
```csharp
[Test]
public void TestController()
{
var testArchitecture = new TestArchitecture();
GameController.SetContextProvider(new TestContextProvider(testArchitecture));
try
{
var controller = new GameController();
controller.Initialize();
}
finally
{
GameController.ResetContextProvider();
}
}
```
## 智能推断规则
### 自动推断的类型
@ -241,6 +293,7 @@ public partial class GameController : IController
public void Initialize()
{
__InjectContextBindings_Generated();
_combat.Initialize(_player, _enemy);
}
@ -263,6 +316,8 @@ public partial class StrategyManager
public IStrategy SelectBestStrategy()
{
__InjectContextBindings_Generated();
return _strategies.FirstOrDefault(s => s.CanExecute())
?? throw new InvalidOperationException("No strategy available");
}
@ -545,9 +600,9 @@ public partial class ServiceManager
}
```
### 5. 在构造函数或初始化方法中调用注入
### 5. 在上下文就绪后的生命周期入口中调用注入
确保在使用字段前调用注入方法
不要把调用点分散到多个位置。优先选择一个明确的入口,例如 `Initialize()``Activate()``_Ready()`,并在方法开头完成注入
```csharp
[ContextAware]
@ -556,20 +611,16 @@ public partial class GameController
{
private IPlayerModel _player = null!;
public GameController()
{
// ✅ 在构造函数中调用
__InjectContextBindings_Generated();
}
public void Initialize()
{
// ✅ 此时字段已注入
__InjectContextBindings_Generated();
_player.Reset();
}
}
```
如果构造函数执行时上下文尚未建立,过早注入会失败;即使在构造函数中调用了注入方法,也不要在调用之前访问这些字段。
## 高级场景
### 泛型类型支持
@ -629,7 +680,8 @@ public partial class GameController
### Q: 可以在构造函数中使用注入的字段吗?
**A**: 不可以。注入方法需要在构造函数中调用,字段在调用后才被注入。推荐在单独的初始化方法中使用。
**A**: 一般不推荐。构造函数阶段通常不是最清晰的生命周期入口,而且在调用注入方法之前字段一定还不可用。推荐做法是在
`Initialize()``_Ready()` 等上下文已就绪的方法开头调用 `__InjectContextBindings_Generated()`,随后再使用这些字段。
```csharp
[ContextAware]
@ -638,15 +690,9 @@ public partial class Controller
{
private IPlayerModel _player = null!;
public Controller()
{
__InjectContextBindings_Generated();
// ❌ 不推荐:在这里使用 _player
}
public void Initialize()
{
// ✅ 推荐:在初始化方法中使用
__InjectContextBindings_Generated();
_player.Reset();
}
}
@ -681,7 +727,7 @@ public partial class Controller
### Q: 如何在测试中模拟注入?
**A**: 配合 `[ContextAware]``SetContextProvider` 方法,使用测试架构
**A**: 配合 `[ContextAware]``SetContextProvider` 方法,先建立测试上下文,再调用类内部已经封装好注入逻辑的公开入口
```csharp
[Test]
@ -695,7 +741,6 @@ public void TestController()
try
{
var controller = new GameController();
controller.__InjectContextBindings_Generated();
controller.Initialize();
// 测试逻辑...
}

View File

@ -459,312 +459,37 @@ public enum ConflictEnum
}
```
### Priority 生成器诊断
### Priority 相关诊断
#### GF_Priority_001 - Priority 只能应用于类
`Priority` 相关规则以专用文档为权威来源:
**错误信息**: `Priority attribute can only be applied to classes`
- 完整生成器诊断见 [Priority 生成器](./priority-generator.md#诊断信息)
- 排序分析器规则见 [与 PriorityUsageAnalyzer 集成](./priority-generator.md#与-priorityusageanalyzer-集成)
**场景**:将 `[Priority]` 特性应用于非类类型
| 诊断 ID | 含义 | 常见修复方向 |
|-------------------------|-------------------------------|------------------------------|
| `GF_Priority_001` | `[Priority]` 只能应用于类 | 仅在 `partial class` 上使用特性 |
| `GF_Priority_002` | 类型已手动实现 `IPrioritized` | 删除特性或删除手写接口实现 |
| `GF_Priority_003` | 标记类型未声明为 `partial` | 为类型添加 `partial` |
| `GF_Priority_004` | 优先级参数无效 | 提供有效的整数优先级值 |
| `GF_Priority_005` | 嵌套类不支持生成 | 将目标类型提取为顶层类 |
| `GF_Priority_Usage_001` | 应优先使用 `GetAllByPriority<T>()` | 对实现 `IPrioritized` 的类型改用排序获取 |
```csharp
[Priority(10)]
public interface IMyInterface // ❌ 错误
{
}
### Context Get 相关诊断
[Priority(10)]
public struct MyStruct // ❌ 错误
{
}
```
`Context Get` 相关规则以专用文档为权威来源:
**解决方案**:只在类上使用 `[Priority]` 特性
- 完整诊断见 [Context Get 注入生成器](./context-get-generator.md#诊断信息)
- 调用时机建议见 [推荐调用时机与模式](./context-get-generator.md#推荐调用时机与模式)
```csharp
[Priority(10)]
public partial class MyClass // ✅ 正确
{
}
```
#### GF_Priority_002 - 已实现 IPrioritized 接口
**错误信息**: `Type already implements IPrioritized interface`
**场景**:类已手动实现 `IPrioritized` 接口,同时使用了 `[Priority]` 特性
```csharp
[Priority(10)]
public partial class MyClass : IPrioritized // ❌ 冲突
{
public int Priority => 10;
}
```
**解决方案**:移除 `[Priority]` 特性或移除手动实现
```csharp
// 方案1移除特性
public partial class MyClass : IPrioritized
{
public int Priority => 10;
}
// 方案2移除手动实现
[Priority(10)]
public partial class MyClass
{
// 自动生成 IPrioritized 实现
}
```
#### GF_Priority_003 - 必须声明为 partial
**错误信息**: `Class must be declared as partial when using Priority attribute`
**场景**:使用 `[Priority]` 特性的类未声明为 `partial`
```csharp
[Priority(10)]
public class MyClass // ❌ 缺少 partial
{
}
```
**解决方案**:添加 `partial` 关键字
```csharp
[Priority(10)]
public partial class MyClass // ✅ 正确
{
}
```
#### GF_Priority_004 - 优先级值无效
**错误信息**: `Priority value is invalid`
**场景**`[Priority]` 特性未提供有效的优先级值
```csharp
[Priority] // ❌ 缺少参数
public partial class MyClass
{
}
```
**解决方案**:提供有效的优先级值
```csharp
[Priority(10)] // ✅ 正确
public partial class MyClass
{
}
```
#### GF_Priority_005 - 不支持嵌套类
**错误信息**: `Nested class is not supported`
**场景**:在嵌套类中使用 `[Priority]` 特性
```csharp
public partial class OuterClass
{
[Priority(10)]
public partial class InnerClass // ❌ 错误
{
}
}
```
**解决方案**:将嵌套类提取为独立的类
```csharp
[Priority(10)]
public partial class InnerClass // ✅ 正确
{
}
```
### Context Get 生成器诊断
#### GF_ContextGet_001 - 不支持嵌套类
**错误信息**: `Class '{ClassName}' cannot use context Get injection inside a nested type`
**场景**:在嵌套类中使用注入特性
```csharp
[ContextAware]
public partial class OuterClass
{
public partial class InnerClass
{
[GetModel] // ❌ 错误
private IModel _model = null!;
}
}
```
**解决方案**:避免在嵌套类中使用注入特性
#### GF_ContextGet_002 - 不支持静态字段
**错误信息**: `Field '{FieldName}' cannot be static when using generated context Get injection`
**场景**:标记静态字段进行注入
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private static IModel _model = null!; // ❌ 错误
}
```
**解决方案**:改为实例字段
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private IModel _model = null!; // ✅ 正确
}
```
#### GF_ContextGet_003 - 不支持只读字段
**错误信息**: `Field '{FieldName}' cannot be readonly when using generated context Get injection`
**场景**:标记只读字段进行注入
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private readonly IModel _model = null!; // ❌ 错误
}
```
**解决方案**:移除 `readonly` 关键字
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private IModel _model = null!; // ✅ 正确
}
```
#### GF_ContextGet_004 - 字段类型不匹配
**错误信息**: `Field '{FieldName}' type '{FieldType}' is not valid for [{AttributeName}]`
**场景**:字段类型与注入特性要求的类型不匹配
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private ISystem _system = null!; // ❌ 错误ISystem 不实现 IModel
}
```
**解决方案**:确保字段类型符合特性要求
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private IModel _model = null!; // ✅ 正确
[GetSystem]
private ISystem _system = null!; // ✅ 正确
}
```
#### GF_ContextGet_005 - 必须是上下文感知类型
**错误信息**: `Class '{ClassName}' must be context-aware to use generated context Get injection`
**场景**:类未标记 `[ContextAware]` 或未实现 `IContextAware`
```csharp
public partial class MyClass // ❌ 缺少 [ContextAware]
{
[GetModel]
private IModel _model = null!;
}
```
**解决方案**:添加 `[ContextAware]` 特性
```csharp
[ContextAware] // ✅ 正确
public partial class MyClass
{
[GetModel]
private IModel _model = null!;
}
```
#### GF_ContextGet_006 - 不支持多个注入特性
**错误信息**: `Field '{FieldName}' cannot declare multiple generated context Get attributes`
**场景**:同一字段标记了多个注入特性
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
[GetSystem] // ❌ 错误:多个特性冲突
private IModel _model = null!;
}
```
**解决方案**:每个字段只标记一个注入特性
```csharp
[ContextAware]
public partial class MyClass
{
[GetModel]
private IModel _model = null!; // ✅ 正确
[GetSystem]
private ISystem _system = null!; // ✅ 正确
}
```
### Priority 使用分析器诊断
#### GF_Priority_Usage_001 - 建议使用 GetAllByPriority
**错误信息**: `Consider using GetAllByPriority<T>() instead of GetAll<T>() for types implementing IPrioritized`
**场景**:获取实现了 `IPrioritized` 的类型时使用 `GetAll<T>()` 而非 `GetAllByPriority<T>()`
```csharp
// ❌ 不推荐:可能未按优先级排序
var systems = context.GetAll<ISystem>();
```
**解决方案**:使用 `GetAllByPriority<T>()` 确保按优先级排序
```csharp
// ✅ 推荐:确保按优先级排序
var systems = context.GetAllByPriority<ISystem>();
```
| 诊断 ID | 含义 | 常见修复方向 |
|---------------------|--------------------|---------------------------------------------------------------|
| `GF_ContextGet_001` | 嵌套类不支持生成注入 | 将目标类型提取为顶层类 |
| `GF_ContextGet_002` | 注入字段不能为 `static` | 改为实例字段 |
| `GF_ContextGet_003` | 注入字段不能为 `readonly` | 移除 `readonly` |
| `GF_ContextGet_004` | 字段类型与注入特性不匹配 | 使用符合特性约束的字段类型 |
| `GF_ContextGet_005` | 目标类型必须具备上下文访问能力 | 添加 `[ContextAware]`、实现 `IContextAware` 或继承 `ContextAwareBase` |
| `GF_ContextGet_006` | 同一字段不能声明多个注入特性 | 每个字段只保留一个注入特性 |
## 性能优势