feat.新增了插件开发文档

This commit is contained in:
lincube
2026-04-13 19:54:37 +08:00
parent ce5acf5bd7
commit 1b22e9df4a
23 changed files with 4770 additions and 1 deletions

View File

@@ -0,0 +1,307 @@
# 01-PluginBase详解
`PluginBase` 是插件的基类,提供基础功能和生命周期管理。本文详细讲解其用法和扩展点。
---
## 🎯 PluginBase 概述
```csharp
public abstract class PluginBase : IPlugin
{
// 日志记录器
protected ILogger? Logger { get; }
// 初始化方法(必须实现)
public abstract void Initialize(HostBuilderContext context, IServiceCollection services);
}
```
---
## 📝 基本用法
### 最小实现
```csharp
using LanMountainDesktop.PluginSdk;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyPlugin;
[PluginEntrance]
public sealed class Plugin : PluginBase
{
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 插件初始化逻辑
}
}
```
---
## 🔧 Initialize 方法详解
### 方法签名
```csharp
public abstract void Initialize(
HostBuilderContext context, // 宿主构建上下文
IServiceCollection services // 服务注册集合
);
```
### 参数说明
| 参数 | 类型 | 用途 |
|-----|------|------|
| `context` | `HostBuilderContext` | 访问宿主配置、环境信息 |
| `services` | `IServiceCollection` | 注册服务、组件、设置页面 |
### context 使用示例
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 访问配置
var configValue = context.Configuration["MySetting"];
// 判断运行环境
var isDevelopment = context.HostingEnvironment.IsDevelopment();
// 获取应用名称
var appName = context.HostingEnvironment.ApplicationName;
}
```
---
## 📝 日志记录
### 使用 Logger 属性
```csharp
[PluginEntrance]
public sealed class Plugin : PluginBase
{
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 记录日志
Logger?.LogInformation("插件初始化开始");
try
{
// 初始化逻辑
services.AddSingleton<IMyService, MyService>();
Logger?.LogInformation("插件初始化完成");
}
catch (Exception ex)
{
Logger?.LogError(ex, "插件初始化失败");
throw;
}
}
}
```
### 日志级别
```csharp
Logger?.LogTrace("详细跟踪信息");
Logger?.LogDebug("调试信息");
Logger?.LogInformation("一般信息");
Logger?.LogWarning("警告信息");
Logger?.LogError("错误信息");
Logger?.LogCritical("严重错误");
```
---
## 🔌 服务注册
### 注册单例服务
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 单例 - 整个应用生命周期只有一个实例
services.AddSingleton<IWeatherService, WeatherService>();
}
```
### 注册作用域服务
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 作用域 - 每个作用域一个实例
services.AddScoped<IDataContext, DataContext>();
}
```
### 注册瞬态服务
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 瞬态 - 每次请求都创建新实例
services.AddTransient<IValidator, Validator>();
}
```
### 带配置的服务注册
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
services.AddSingleton<IWeatherService>(provider =>
{
var httpClient = provider.GetRequiredService<HttpClient>();
var logger = provider.GetRequiredService<ILogger<WeatherService>>();
var apiKey = context.Configuration["WeatherApiKey"];
return new WeatherService(httpClient, logger, apiKey);
});
}
```
---
## 🧩 完整示例
```csharp
using LanMountainDesktop.PluginSdk;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WeatherPlugin;
[PluginEntrance]
public sealed class Plugin : PluginBase
{
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
Logger?.LogInformation("天气插件初始化开始");
try
{
// 1. 注册 HTTP 客户端
services.AddHttpClient("weather", client =>
{
client.BaseAddress = new Uri("https://api.weather.com/");
client.Timeout = TimeSpan.FromSeconds(30);
});
// 2. 注册服务
services.AddSingleton<IWeatherService, WeatherService>();
services.AddSingleton<ILocationService, LocationService>();
// 3. 注册桌面组件
services.AddPluginDesktopComponent<WeatherWidget>(
new PluginDesktopComponentOptions
{
ComponentId = "WeatherPlugin.Widget",
DisplayName = "天气",
IconKey = "Weather",
Category = "信息",
MinWidthCells = 4,
MinHeightCells = 3
});
// 4. 注册设置页面
services.AddPluginSettingsSection(
"weather-settings",
"天气设置",
section => section
.AddText("api_key", "API密钥", isPassword: true)
.AddText("default_city", "默认城市", defaultValue: "北京")
.AddToggle("auto_refresh", "自动刷新", defaultValue: true)
.AddNumber("refresh_interval", "刷新间隔(分钟)",
defaultValue: 30, minimum: 5, maximum: 120),
iconKey: "Settings");
Logger?.LogInformation("天气插件初始化完成");
}
catch (Exception ex)
{
Logger?.LogError(ex, "天气插件初始化失败");
throw;
}
}
}
```
---
## 💡 最佳实践
### 1. 使用 try-catch 包装初始化逻辑
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
try
{
// 初始化逻辑
}
catch (Exception ex)
{
Logger?.LogError(ex, "初始化失败");
throw; // 重新抛出,让宿主知道初始化失败
}
}
```
### 2. 按依赖顺序注册服务
```csharp
// ✅ 先注册被依赖的服务
services.AddSingleton<IDataService, DataService>();
// 再注册依赖它们的服务
services.AddSingleton<IWeatherService, WeatherService>(); // 依赖 IDataService
// 最后注册组件
services.AddPluginDesktopComponent<WeatherWidget>(options);
```
### 3. 记录初始化过程
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
Logger?.LogInformation("开始初始化...");
Logger?.LogDebug("注册服务...");
services.AddSingleton<IMyService, MyService>();
Logger?.LogDebug("注册组件...");
services.AddPluginDesktopComponent<MyWidget>(options);
Logger?.LogInformation("初始化完成");
}
```
---
## 📚 参考资源
- [PluginBase 源码](../../LanMountainDesktop.PluginSdk/PluginBase.cs)
- [IPlugin 接口](../../LanMountainDesktop.PluginSdk/IPlugin.cs)
- [Microsoft.Extensions.DependencyInjection 文档](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection)
---
## 🎯 下一步
学习组件注册 API
👉 **[02-组件注册与配置](02-组件注册与配置.md)**
---
*最后更新2026年4月*

View File

@@ -0,0 +1,182 @@
# 02-组件注册与配置
`AddPluginDesktopComponent` 是注册桌面组件的核心 API。本文详细讲解其用法和配置选项。
---
## 🎯 API 概览
```csharp
public static IServiceCollection AddPluginDesktopComponent<TComponent>(
this IServiceCollection services,
PluginDesktopComponentOptions options)
where TComponent : class, IControl
```
---
## 📋 基本用法
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
services.AddPluginDesktopComponent<MyWidget>(
new PluginDesktopComponentOptions
{
ComponentId = "MyPlugin.MyWidget",
DisplayName = "我的组件",
IconKey = "Home",
Category = "工具",
MinWidthCells = 4,
MinHeightCells = 3
});
}
```
---
## 🔧 PluginDesktopComponentOptions
### 完整属性列表
| 属性 | 类型 | 必需 | 说明 |
|-----|------|------|------|
| `ComponentId` | `string` | ✅ | 唯一标识符 |
| `DisplayName` | `string` | ✅ | 显示名称 |
| `IconKey` | `string` | ✅ | 图标键名 |
| `Category` | `string` | ✅ | 分类 |
| `MinWidthCells` | `int` | ✅ | 最小宽度(格) |
| `MinHeightCells` | `int` | ✅ | 最小高度(格) |
| `CornerRadiusPreset` | `PluginCornerRadiusPreset` | ❌ | 圆角预设 |
| `ResizeMode` | `PluginDesktopComponentResizeMode` | ❌ | 调整大小模式 |
### ComponentId
```csharp
ComponentId = "MyPlugin.WeatherWidget"
```
- 必须唯一
- 建议使用 `插件ID.组件名` 格式
- 一经发布不可更改
### DisplayName
```csharp
DisplayName = "天气"
```
- 显示在组件库中
- 支持本地化(通过资源文件)
### IconKey
```csharp
IconKey = "Weather"
```
使用 [Fluent UI System Icons](https://github.com/microsoft/fluentui-system-icons) 的图标名。
### Category
```csharp
Category = "工具"
```
常用分类:
- `工具` - 实用工具
- `信息` - 信息展示
- `娱乐` - 娱乐相关
- `系统` - 系统监控
### MinWidthCells / MinHeightCells
```csharp
MinWidthCells = 4, // 4格宽约240像素
MinHeightCells = 3 // 3格高约180像素
```
---
## 🎨 圆角配置
```csharp
services.AddPluginDesktopComponent<MyWidget>(
new PluginDesktopComponentOptions
{
ComponentId = "MyPlugin.Widget",
DisplayName = "我的组件",
IconKey = "Home",
Category = "工具",
MinWidthCells = 4,
MinHeightCells = 3,
CornerRadiusPreset = PluginCornerRadiusPreset.Component
});
```
---
## 📐 调整大小模式
```csharp
services.AddPluginDesktopComponent<MyWidget>(
new PluginDesktopComponentOptions
{
// ...
ResizeMode = PluginDesktopComponentResizeMode.Free
});
```
| 模式 | 说明 |
|-----|------|
| `Free` | 自由调整大小 |
| `Fixed` | 固定大小 |
| `AspectRatio` | 保持宽高比 |
---
## 🧩 完整示例
```csharp
public override void Initialize(HostBuilderContext context, IServiceCollection services)
{
// 天气组件
services.AddPluginDesktopComponent<WeatherWidget>(
new PluginDesktopComponentOptions
{
ComponentId = "WeatherPlugin.Widget",
DisplayName = "天气",
IconKey = "Weather",
Category = "信息",
MinWidthCells = 4,
MinHeightCells = 3,
CornerRadiusPreset = PluginCornerRadiusPreset.Component,
ResizeMode = PluginDesktopComponentResizeMode.Free
});
// 时钟组件
services.AddPluginDesktopComponent<ClockWidget>(
new PluginDesktopComponentOptions
{
ComponentId = "ClockPlugin.Widget",
DisplayName = "时钟",
IconKey = "Clock",
Category = "工具",
MinWidthCells = 4,
MinHeightCells = 4,
CornerRadiusPreset = PluginCornerRadiusPreset.Component,
ResizeMode = PluginDesktopComponentResizeMode.AspectRatio
});
}
```
---
## 📚 参考资源
- [PluginDesktopComponentOptions 源码](../../LanMountainDesktop.PluginSdk/PluginDesktopComponentOptions.cs)
- [02-桌面组件系统](../02-核心概念与原理/02-桌面组件系统.md)
---
*最后更新2026年4月*

View File

@@ -0,0 +1,147 @@
# 03-设置API详解
设置 API 允许插件添加配置页面和持久化用户设置。
---
## 🎯 API 概览
### 声明式设置
```csharp
services.AddPluginSettingsSection(
string sectionId,
string displayName,
Action<PluginSettingsSectionBuilder> configure,
string iconKey);
```
### 自定义设置页
```csharp
services.AddPluginSettingsSection<TPage>(
string sectionId,
string displayName,
string iconKey)
where TPage : SettingsPageBase;
```
---
## 📋 声明式设置详解
### 基本用法
```csharp
services.AddPluginSettingsSection(
"myplugin-settings",
"我的设置",
section => section
.AddToggle("enabled", "启用", defaultValue: true)
.AddText("name", "名称", defaultValue: ""),
iconKey: "Settings");
```
### 设置类型
#### Toggle开关
```csharp
.AddToggle(
key: "auto_update",
displayName: "自动更新",
defaultValue: true,
description: "启动时检查更新")
```
#### Text文本
```csharp
.AddText(
key: "api_key",
displayName: "API密钥",
defaultValue: "",
placeholder: "请输入",
isPassword: false)
```
#### Number数值
```csharp
.AddNumber(
key: "interval",
displayName: "刷新间隔",
defaultValue: 60,
minimum: 10,
maximum: 3600,
increment: 10)
```
#### Select选择
```csharp
.AddSelect(
key: "theme",
displayName: "主题",
choices: new[]
{
new SettingsOptionChoice("light", "浅色"),
new SettingsOptionChoice("dark", "深色")
},
defaultValue: "light")
```
#### Path路径
```csharp
.AddPath(
key: "save_path",
displayName: "保存路径",
defaultValue: "",
pathType: SettingsPathType.Folder,
dialogTitle: "选择文件夹")
```
---
## 🔧 读取和保存设置
### 使用 IPluginSettingsService
```csharp
public class MyService
{
private readonly IPluginSettingsService _settings;
public MyService(IPluginSettingsService settings)
{
_settings = settings;
// 读取
var value = _settings.GetValue<string>("key", "default");
// 保存
_settings.SetValue("key", "new value");
// 监听变化
_settings.SettingsChanged += (s, e) =>
{
if (e.Key == "key")
{
HandleChange(e.NewValue);
}
};
}
}
```
---
## 📚 参考资源
- [IPluginSettingsService 源码](../../LanMountainDesktop.PluginSdk/IPluginSettingsService.cs)
- [03-设置系统集成](../02-核心概念与原理/03-设置系统集成.md)
---
*最后更新2026年4月*

View File

@@ -0,0 +1,106 @@
# 04-外观API详解
外观 API 提供圆角、主题等视觉相关的功能。
---
## 🎯 IPluginAppearanceContext
```csharp
public interface IPluginAppearanceContext
{
// 获取圆角值
CornerRadius ResolveCornerRadius(PluginCornerRadiusPreset preset);
// 获取带限制的圆角值
CornerRadius ResolveCornerRadius(
PluginCornerRadiusPreset preset,
CornerRadius? minimum,
CornerRadius? maximum);
// 获取缩放后的圆角值
CornerRadius ResolveScaledCornerRadius(
double baseRadius,
double? minimum,
double? maximum);
// 外观变化事件
event EventHandler? AppearanceChanged;
}
```
---
## 📐 圆角 API
### 获取圆角值
```csharp
public MyWidget(PluginDesktopComponentContext context)
{
// 使用预设
CornerRadius = context.Appearance.ResolveCornerRadius(
PluginCornerRadiusPreset.Component);
}
```
### 带限制的圆角
```csharp
var radius = context.Appearance.ResolveCornerRadius(
PluginCornerRadiusPreset.Component,
minimum: new CornerRadius(8),
maximum: new CornerRadius(24));
```
### 缩放圆角
```csharp
var radius = context.Appearance.ResolveScaledCornerRadius(
baseRadius: 16,
minimum: 8,
maximum: 32);
```
---
## 🎨 圆角预设
| 预设 | 值 | 用途 |
|-----|---|------|
| Micro | 6px | 微小元素 |
| Xs | 12px | 小元素 |
| Sm | 14px | 小卡片 |
| Md | 20px | 普通按钮 |
| Lg | 28px | 大面板 |
| Xl | 32px | 强调容器 |
| Island | 36px | 大型容器 |
| Component | 18px | 桌面组件 |
| Default | 自适应 | 自动计算 |
---
## 🔄 响应外观变化
```csharp
public MyWidget(PluginDesktopComponentContext context)
{
context.Appearance.AppearanceChanged += (_, _) =>
{
// 重新应用圆角
CornerRadius = context.Appearance.ResolveCornerRadius(
PluginCornerRadiusPreset.Component);
};
}
```
---
## 📚 参考资源
- [IPluginAppearanceContext 源码](../../LanMountainDesktop.PluginSdk/IPluginAppearanceContext.cs)
- [04-外观与主题系统](../02-核心概念与原理/04-外观与主题系统.md)
---
*最后更新2026年4月*

View File

@@ -0,0 +1,73 @@
# 05-本地化支持
本地化 API 支持多语言资源管理。
---
## 🎯 资源文件
### 文件位置
```
Localization/
├── zh-CN.json # 简体中文
├── en-US.json # 英文
├── ja-JP.json # 日文
└── ko-KR.json # 韩文
```
### 资源格式
```json
{
"PluginName": "我的插件",
"Settings": {
"Title": "设置",
"Save": "保存"
},
"Messages": {
"Hello": "你好,{0}!",
"Error": "错误:{0}"
}
}
```
---
## 📝 使用本地化
### 注入 IStringLocalizer
```csharp
public class MyService
{
private readonly IStringLocalizer<MyService> _localizer;
public MyService(IStringLocalizer<MyService> localizer)
{
_localizer = localizer;
}
public void DoWork()
{
// 简单字符串
var name = _localizer["PluginName"];
// 带参数
var message = _localizer["Messages.Hello", "用户"];
// 嵌套键
var title = _localizer["Settings.Title"];
}
}
```
---
## 📚 参考资源
- [Microsoft.Extensions.Localization 文档](https://docs.microsoft.com/dotnet/api/microsoft.extensions.localization)
---
*最后更新2026年4月*