Healnet.Core
3.0.0
dotnet add package Healnet.Core --version 3.0.0
NuGet\Install-Package Healnet.Core -Version 3.0.0
<PackageReference Include="Healnet.Core" Version="3.0.0" />
<PackageVersion Include="Healnet.Core" Version="3.0.0" />
<PackageReference Include="Healnet.Core" />
paket add Healnet.Core --version 3.0.0
#r "nuget: Healnet.Core, 3.0.0"
#:package Healnet.Core@3.0.0
#addin nuget:?package=Healnet.Core&version=3.0.0
#tool nuget:?package=Healnet.Core&version=3.0.0
Healnet.Core 核心契约层
版本: v2.0.6 | TFM: net10.0 | 依赖: Healnet.Common | NuGet: Healnet.Core 2.0.6
概述
Healnet.Core 是 Healnet 微服务框架的核心契约层,提供领域驱动设计(DDD)基础设施、统一异常体系、仓储/缓存/日志抽象、API 响应格式、微服务通用能力抽象,以及 AI 能力的抽象契约。它只定义抽象契约与 POCO,不携带任何具体技术 SDK 依赖——这是"依赖倒置(DIP)"的关键:上层 Infrastructure 实现这些契约,而契约本身保持稳定、可被任意宿主复用。
⭐ AI 能力已彻底 DIP:所有 AI 抽象接口、选项 POCO、上下文模型、记忆契约/实体已上移至本层(
Healnet.Core.AI/Healnet.Core.AI.Memory)。Core 的csproj不引用 Microsoft.Extensions.AI / Semantic Kernel / Agent Framework——这些契约是纯接口 + POCO,与具体 AI 框架完全解耦。具体实现(如UnifiedAIService)在Healnet.Infrastructure.AI。
⚠️ 重要说明:
- Core 不提供
AddCore()之类的 DI 注册方法。它仅包含契约与抽象;具体注册在Healnet.Infrastructure或宿主项目完成。- Core 不含 MediatR / CQRS(
ICommand/IQuery/IMediator并非库 API,仅旧文档示例残留)。- 旧文档出现的
Enumeration、Filtering类型不存在于源码。
核心特性
- ✅ DDD 实体 -
Entity<TKey>/AggregateRoot<TKey>/ValueObject/AuditableEntity/SoftDeleteEntity/DomainEvent - ✅ 统一异常 - 7 种 HTTP 业务异常 + 协议异常(带固定 ErrorCode)
- ✅ 仓储模式 -
IRepository<T,TKey>/IReadOnlyRepository<T,TKey>泛型接口 - ✅ 工作单元 -
IUnitOfWork(事务抽象) - ✅ 服务基类 -
BaseService/CrudService<TEntity,TRequest,TResponse,TKey> - ✅ API 响应 -
ApiResponse/ApiResponse<T>/PagedResponse<T> - ✅ 消息队列抽象 -
IMessagePublisher/IMessageSubscriber - ✅ 缓存/日志抽象 -
ICacheService/ILoggerService - ✅ 微服务抽象 - 认证(
ITokenService)、服务发现(IConsulService/IConsulHttpClient)、HTTP(IHttpClientService)、幂等、功能开关、请求上下文、发件箱、API 版本 - ✅ AI 契约 ⭐ -
IAIService/IAgentService/ICopilotClient/IAgentContextManager/IChatContextManager/IRAGService+ Memory 三契约
核心组件
1. 实体与值对象 (Entities) — 命名空间 Healnet.Core.Entities
| 类型 | 说明 |
|---|---|
Entity<TKey> (abstract) |
实体基类:TKey Id;重写 Equals/GetHashCode/==/!=;IEquatable<Entity<TKey>> |
Entity (abstract) |
Entity<long> 便捷基类 |
AggregateRoot<TKey> (abstract) |
继承 Entity<TKey>,支持领域事件收集:DomainEvents、AddDomainEvent/RemoveDomainEvent/ClearDomainEvents/DequeueDomainEvents |
ValueObject (abstract) |
值对象基类:基于 GetEqualityComponents() 的值相等性 |
AuditableEntity<TKey> (abstract) |
可审计实体:CreatedAt/CreatedBy/UpdatedAt/UpdatedBy/IsDeleted/DeletedAt/DeletedBy |
SoftDeleteEntity<TKey> (abstract) |
软删除实体:IsDeleted/DeletedAt |
IDomainEvent / DomainEvent |
领域事件接口与基类:OccurredOn(UtcNow)、EventId |
IDomainEventDispatcher / IDomainEventHandler<in TEvent> |
领域事件分发抽象(实现在宿主/Infrastructure) |
2. 异常体系 (Exceptions) — 命名空间 Healnet.Core.Exceptions
基类 HealnetException : Exception,含 int ErrorCode、string UserMessage、bool IsRetryable。
| 类型 | HTTP 状态 | ErrorCode |
|---|---|---|
BadRequestException |
400 | 400(可自定义) |
BusinessException |
400 | 可自定义 |
UnauthorizedException |
401 | — |
ForbiddenException |
403 | — |
NotFoundException |
404 | — |
ValidationException |
422 | Dictionary<string,string[]> Errors(静态 WithError/WithErrors) |
协议异常(带固定 ErrorCode,部分可重试):SqlInjectionException(4001)、PermissionDeniedException(4031)、ResourceNotFoundException(4041)、ValidationFailedException(4002)、DatabaseException(5001,可重试)、LLMException(5002,可重试)、TimeoutExceptionEx(5041,可重试)、RateLimitedException(4291,可重试)。
3. 接口抽象 (Interfaces) — 命名空间 Healnet.Core.Interfaces
| 接口 | 说明 |
|---|---|
IRepository<TEntity,TKey> : IReadOnlyRepository<...> |
完整仓储:AddAsync/AddRangeAsync/UpdateAsync/UpdateRangeAsync/DeleteAsync(id)/DeleteAsync(entity)/DeleteRangeAsync |
IReadOnlyRepository<TEntity,TKey> |
查询:GetByIdAsync/GetAllAsync/GetPagedAsync(page,pageSize)/CountAsync/ExistsAsync/FindAsync/FindAllAsync |
IUnitOfWork : IDisposable |
SaveChangesAsync(ct)/BeginTransactionAsync/CommitTransactionAsync/RollbackTransactionAsync/HasActiveTransaction |
ICacheService |
GetAsync<T>/SetAsync<T>/RemoveAsync/ExistsAsync/GetOrSetAsync<T>/GetKeysByPatternAsync/RemoveByPatternAsync/ClearAsync/GetTtlAsync |
ILoggerService |
Trace/Debug/Information/Warning/Error/Critical/Error(Exception,...)/Log(LogLevel,...) |
IMessagePublisher |
PublishAsync<T>(exchange+routingKey / queue / 单消息 / 带 MessageOptions) |
IMessageSubscriber |
Subscribe<T>/StartConsumingAsync/StopConsumingAsync |
IService<TRequest,TResponse,TKey> |
标准服务接口:GetByIdAsync/GetAllAsync/GetPagedAsync/CreateAsync/UpdateAsync/DeleteAsync,返回 ApiResponse 系列 |
4. AI 契约 ⭐ — 命名空间 Healnet.Core.AI
纯接口 + POCO,不引用任何 AI SDK。
接口:
| 接口 | 关键成员 |
|---|---|
IAIService |
ChatAsync(prompt[,contextId])、SummarizeAsync、TranslateAsync、ExecuteAgentAsync、ExecuteAgentWithToolsAsync、ClearContext、AIProvider GetCurrentProvider() |
IAgentService |
ExecuteAsync/ExecuteWithToolsAsync/RegisterAgentAsync/RegisterToolAsync/ChatAsync |
ICopilotClient |
ChatAsync/SummarizeAsync/TranslateAsync/ClearContext |
IAgentContextManager |
CreateContextAsync(agentName)/DeleteContextAsync/GetContextAsync→AgentContext?/ClearAllContextsAsync |
IChatContextManager |
CreateContextAsync()/DeleteContextAsync/GetContextAsync→ChatContext?/ClearAllContextsAsync |
IRAGService |
AddDocumentAsync/RemoveDocumentAsync/SearchDocumentsAsync(query,topK=5)→List<Document>/ChatWithRAGAsync |
选项 / 枚举(POCO):
AIOptions:Provider(AIProvider)、Framework(AIFramework)、ApiKey、Endpoint、ModelName("gpt-4o")、MaxTokens(4096)、Temperature(0.7)、TopP(0.9)、ContextWindowSize(8192)、RAG(RAGOptions)、AgentFramework(AgentFrameworkOptions)enum AIProvider { SemanticKernel, MicrosoftAI, Custom }enum AIFramework { SemanticKernel, AgentFramework, Hybrid }RAGOptions:Enabled(true)、TopK(5)、MaxContextLength(3000)AgentFrameworkOptions:Endpoint、DeploymentName("gpt-4o")、EnableToolCalling(true)、MaxIterations(10)、Dictionary<string,string> Tools
上下文模型(POCO,框架无关):
AgentContext:ContextId/AgentName/List<AgentMessage> Messages/AddUserMessage/AddAssistantMessage/ClearHistoryAgentMessage:Role/Content/Timestamp/MetadataChatContext:仅含List<ChatMessage> Messages(不依赖 Semantic Kernel 的ChatHistory)、AddUserMessage/AddAssistantMessage/ClearHistoryChatMessage:Role/Content/TimestampDocument:Id/Content/Metadata/Score
5. AI 记忆契约 ⭐ — 命名空间 Healnet.Core.AI.Memory
Contracts(接口 + 配置/记录 POCO):
| 类型 | 说明 |
|---|---|
IShortTermMemoryStore |
L1 短期记忆:GetWindowAsync(sessionId)→List<ShortTermTurn>、AppendAsync、ClearAsync(默认基于 Redis) |
IConversationRepository |
L2 关系型库:EnsureSchemaAsync/SaveSessionAsync/GetSessionAsync/SaveTurnAsync/GetRecentTurnsAsync/ListSessionsAsync |
IMemoryOrchestrator |
编排:BuildContextAsync(sessionId,userId,domain?,enableMemory)→MemoryContext、RecordTurnAsync(MemoryRecordInput)、GetHistoryAsync |
MemoryContext |
List<ShortTermTurn> ShortTermHistory |
MemoryOptions |
EnableShortTerm(true)、ShortTermWindowTurns(10)、ShortTermTtlMinutes(30)、EnableFullConversation(true)、ConversationDbConfigId("conversation") |
MemoryRecordInput (record) |
SessionId/UserId/Domain?/DatabaseName?/UserQuery/AssistantResponse?/IsValid/RowCount/ErrorMessage?/DurationMs/TokensUsed |
ShortTermTurn |
Role/Content/Ts(DateTime) |
Entities(纯 POCO,无 ORM 特性;映射在 Infrastructure 的 SqlSugar Fluent):
ConversationSession:Id/SessionId/UserId/Domain?/DatabaseName?/Title?/Status(1=active)/CreatedAt/UpdatedAtConversationTurn:Id/SessionId/TurnNo/UserId/Domain?/DatabaseName?/UserQuery?/Response?/IsValid/RowCount/ErrorMessage?/TokensUsed/DurationMs/Status(1)/CreatedAt
6. 服务基类 (Services) — 命名空间 Healnet.Core.Services
| 类型 | 说明 |
|---|---|
BaseService (abstract) |
持有 protected ILoggerService Logger;ValidateId/ValidateNotNull/ValidateNotEmpty/GetEntityOrThrowAsync/LogError/LogInformation |
CrudService<TEntity,TRequest,TResponse,TKey> : BaseService, IService<...> |
标准 CRUD 实现;抽象 MapToEntity/MapToResponse/UpdateEntity,虚 ValidateRequest |
7. API 响应 (Responses) — 命名空间 Healnet.Core.Responses
| 类型 | 说明 |
|---|---|
ApiResponse (非泛型) |
Code/Message/Data/Timestamp/Path/IsSuccess;静态 Success/Fail/Unauthorized/Forbidden/NotFound/BadRequest |
ApiResponse<T> |
泛型版,静态 Success(T?,msg)/Fail(msg,code)/NotFound(msg) 等 |
PagedResponse<T> |
Code/Message/List<T> Data/Total/Page/PageSize/TotalPages/HasNextPage/HasPreviousPage;静态 Create(...) |
8. 其他模块
| 模块 | 命名空间 | 说明 |
|------|----------|------|
| 全局异常中间件 | Core.Middleware | ExceptionHandlerMiddleware(捕获异常→ApiResponse,映射 400/401/403/404/422/500);app.UseExceptionHandlerMiddleware() |
| 幂等性 | Core.Filters | [Idempotent] 特性(TtlSeconds=3600、HeaderName="Idempotency-Key")+ IIdempotencyStore |
| API 版本 | Core.Versioning | [ApiVersion] 特性 + ApiVersionConstants(RouteTemplate/DefaultVersion="1.0"/VersionHeader="X-Api-Version") |
| 发件箱 | Core.Outbox | OutboxMessage(OutboxMessageStatus 枚举:Pending/Delivered/DeadLetter)+ IOutboxStore| | 功能开关 |Core.Features|IFeatureFlagService(IsEnabledAsync/GetValueAsync<T>/GetEnabledFeaturesAsync)+ FeatureContext| | 请求上下文 |Core.Context|IRequestContext(TraceId/TenantId/UserId/UserName/ClientIp/UserAgent)+ DefaultRequestContext(AsyncLocal) | | 认证抽象 | Core.Authentication|ITokenService+JwtOptions(实现在 Infrastructure.Authentication) | | 服务发现抽象 | Core.Consul|IConsulService+IConsulHttpClient+ConsulOptions(实现在 Infrastructure.Consul) | | HTTP 抽象 | Core.Http|IHttpClientService+IHttpClientFactoryService+IHttpInterceptor(实现在 Infrastructure.Http) | | Skill | Core.Skill|ISkillLoader+SkillOptions(SkillStorageMode:Local/Oss)+ OssOptions` |
依赖关系
graph LR
A[Healnet.Core] --> B[Healnet.Common]
A --> C[Microsoft.Extensions.Logging.Abstractions]
A --> D[Microsoft.AspNetCore.Http.Abstractions]
A --> E[Microsoft.Extensions.Primitives]
⚠️ 注意:Core 仅依赖上述 3 个轻量 NuGet 包 + Common。无 Semantic Kernel / Microsoft.Extensions.AI / MediatR / SqlSugar / EF Core 等任何重量级依赖。
使用指南
1. 创建实体
using Healnet.Core.Entities;
public class User : Entity<long>
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
public class Product : AuditableEntity
{
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
public class Article : SoftDeleteEntity
{
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
}
2. 统一异常处理
using Healnet.Core.Exceptions;
throw new BusinessException("库存不足"); // → 400
throw new NotFoundException($"用户 {userId} 不存在"); // → 404
throw new ValidationException(new List<string> { "邮箱格式不正确" }); // → 422
throw new ForbiddenException("无权访问此资源"); // → 403
3. API 响应格式
using Healnet.Core.Responses;
return ApiResponse<User>.Success(user, "查询成功");
return ApiResponse.Error(400, "参数错误");
var paged = PagedResponse<User>.Create(users, page, pageSize, totalCount);
4. 仓储接口
using Healnet.Core.Interfaces;
public interface IUserRepository : IRepository<User, long>
{
Task<User?> GetByEmailAsync(string email);
Task<IEnumerable<User>> GetActiveUsersAsync();
}
5. 服务基类
using Healnet.Core.Services;
using Healnet.Core.Interfaces;
public class UserService : BaseService, IUserService
{
private readonly IRepository<User, long> _repository;
public UserService(ILoggerService logger, IRepository<User, long> repository) : base(logger)
=> _repository = repository;
public async Task<User> GetByIdAsync(long id)
{
ValidateId(id);
var user = await _repository.GetByIdAsync(id);
if (user is null) throw new NotFoundException($"用户 {id} 不存在");
return user;
}
}
6. 全局异常处理中间件
// Program.cs — 推荐用 Core 版(功能最全,支持 Path/Timestamp)
app.UseExceptionHandlerMiddleware();
7. 使用 AI 契约(消费方视角)
using Healnet.Core.AI;
public class ChatController
{
private readonly ICopilotClient _copilot;
public ChatController(ICopilotClient copilot) => _copilot = copilot;
public async Task<string> Ask(string prompt)
=> await _copilot.ChatAsync(prompt); // 实现由 Infrastructure.AI 注入
}
NuGet 包信息
| 属性 | 值 |
|---|---|
| PackageId | Healnet.Core |
| 当前版本 | 2.0.6 |
| 目标框架 | net10.0 |
| 依赖项目 | Healnet.Common |
| 主要依赖 | Microsoft.Extensions.Logging.Abstractions [9.0.0,11.0.0)、Microsoft.AspNetCore.Http.Abstractions [2.2.0,3.0.0)、Microsoft.Extensions.Primitives [9.0.0,11.0.0) |
| 仓库 | 内部仓库 |
版本历史
| 版本 | 日期 | 变更说明 |
|---|---|---|
| v2.0.6 | 2026-07-10 | BusinessConfig 全套迁出至业务项目;IEntityMapper 接口引入支持可插拔 Fluent 映射 |
| v2.0.4 | 2026-07-08 | AI 层彻底 DIP:抽象契约/POCO/记忆实体上提 Core.AI/Core.AI.Memory;ChatContext 去 Semantic Kernel 依赖;0 错误 0 警告 |
| v2.0.0 | — | 版本统一升级至 2.x;移除 Newtonsoft.Json |
| v1.5.0 | 2026-06-16 | 新增 AggregateRoot<T>、ValueObject、DomainEvent;新增认证/Consul/HTTP 抽象契约 |
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Healnet.Common (>= 3.0.0)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0 && < 3.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.0 && < 11.0.0)
- Microsoft.Extensions.Primitives (>= 9.0.0 && < 11.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Healnet.Core:
| Package | Downloads |
|---|---|
|
Healnet.Infrastructure
Healnet.Infrastructure 是 Healnet 框架的基础设施层类库,提供各种基础设施服务的封装和集成,包括 Consul 服务发现、Redis 缓存、RabbitMQ 消息队列、gRPC、Elasticsearch、Milvus 向量数据库、SQLSugar ORM、JWT 认证、YARP 反向代理、OpenTelemetry 可观测性、Serilog 日志框架、ClickHouse 列式数据库等。 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.0.0 | 40 | 7/16/2026 |
| 2.0.7 | 99 | 7/10/2026 |
| 2.0.5 | 99 | 7/8/2026 |
| 2.0.3 | 107 | 6/30/2026 |
| 2.0.0 | 111 | 6/29/2026 |
| 1.7.3 | 104 | 6/29/2026 |
| 1.5.0 | 132 | 6/16/2026 |
| 1.4.0 | 109 | 6/15/2026 |
| 1.2.0 | 110 | 5/29/2026 |
| 1.1.1 | 106 | 5/25/2026 |
| 1.1.0 | 113 | 5/22/2026 |
| 1.0.9 | 116 | 5/20/2026 |
| 1.0.8 | 104 | 5/20/2026 |
| 1.0.7 | 101 | 5/20/2026 |
| 1.0.6 | 134 | 5/19/2026 |
| 1.0.5 | 151 | 5/13/2026 |
| 1.0.4 | 114 | 5/13/2026 |
| 1.0.3 | 119 | 5/13/2026 |
| 1.0.2 | 110 | 5/13/2026 |
| 1.0.1 | 112 | 5/13/2026 |
v3.0.0: 随 Healnet 统一升版至 3.0.0(破坏性变更来自 Healnet.Common:AESCrypto 移除无参重载、AESDecrypt 改返回元组)。v2.0.7: 三库版本统一 2.0.7;BusinessConfig 全套迁出至业务项目;BusinessExample 迁出;ConversationArchive 泛化。v2.0.6: 三库版本统一 2.0.6。v2.0.3: 统一三库版本号;升级目标框架至 net10.0;更新所有依赖包至最新稳定版。v2.0.1: 依赖包版本升级,修复若干已知问题。v2.0.0: 重大版本更新,目标框架从 net8.0 升级至 net10.0,全面更新依赖包版本。