TJC.Cyclops.Common.Service 2026.1.7.1

dotnet add package TJC.Cyclops.Common.Service --version 2026.1.7.1
                    
NuGet\Install-Package TJC.Cyclops.Common.Service -Version 2026.1.7.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TJC.Cyclops.Common.Service" Version="2026.1.7.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TJC.Cyclops.Common.Service" Version="2026.1.7.1" />
                    
Directory.Packages.props
<PackageReference Include="TJC.Cyclops.Common.Service" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TJC.Cyclops.Common.Service --version 2026.1.7.1
                    
#r "nuget: TJC.Cyclops.Common.Service, 2026.1.7.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TJC.Cyclops.Common.Service@2026.1.7.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TJC.Cyclops.Common.Service&version=2026.1.7.1
                    
Install as a Cake Addin
#tool nuget:?package=TJC.Cyclops.Common.Service&version=2026.1.7.1
                    
Install as a Cake Tool

Cyclops.Common.Service

项目概述

Cyclops.Common.Service是企服版框架中的核心服务处理库,提供了服务层的基础设施和后台任务管理功能。该项目主要关注两个核心方面:

  1. 为应用程序提供标准化的服务层实现模式
  2. 提供强大且灵活的后台任务处理框架

通过统一的服务模式和后台任务管理,Cyclops.Common.Service使开发者能够轻松构建可靠、可扩展的企业级应用服务。

核心功能模块

1. 基础服务框架

1.1 基础服务类
  • BaseService:所有服务类的基类,提供了服务的基本功能和生命周期管理
  • BaseServiceT<T>:泛型版本的基础服务类,允许在服务中指定实体类型
1.2 服务特性
  • 依赖注入集成:与Cyclops.DI深度集成,支持自动依赖注入
  • 异常处理:内置统一的异常处理机制,确保服务层的异常能够被适当捕获和处理
  • 日志记录:集成日志功能,便于服务操作的跟踪和调试

2. 后台任务框架

2.1 任务基类
  • BaseJobService:后台任务的基础实现,所有后台任务都应继承此类
  • BaseSubJobService:子任务的基类,用于实现可分解的复杂任务
  • ParentJobService:父任务服务,用于管理和协调多个子任务
2.2 任务接口
  • IJob:所有作业任务必须实现的接口,定义了作业的基本操作
2.3 任务管理
  • JobServiceLoader:作业服务加载器,负责发现和初始化系统中的作业服务
  • JobInfosCache:作业信息缓存,用于存储和管理作业的元数据
  • JobInfo:作业信息模型,包含作业的各种属性和状态信息
2.4 后台服务基础设施
  • BaseBackgroundService:基于.NET Core的BackgroundService的增强实现,提供更丰富的后台任务管理功能

技术栈

  • 开发框架:.NET 8.0
  • 项目类型:类库(Class Library)
  • 核心依赖
    • Cyclops.Common - 提供基础工具类
    • Cyclops.DI - 依赖注入框架
    • Microsoft.Extensions.Hosting - 后台服务支持

环境依赖要求

  • .NET 8.0 SDK 或更高版本
  • 引用的Cyclops.Common和Cyclops.DI项目

安装与配置

安装方式

可以通过以下方式安装Cyclops.Common.Service包:

  1. NuGet包管理器

    Install-Package TJC.Cyclops.Common.Service
    
  2. .NET CLI

    dotnet add package TJC.Cyclops.Common.Service
    

基本配置

在使用Cyclops.Common.Service之前,需要进行以下配置:

  1. 依赖注入配置:在应用程序的启动类中配置服务注入
  2. 后台服务配置:对于后台任务服务,需要在HostBuilder中注册

核心功能代码示例

1. 创建和使用基础服务

// 定义服务接口
public interface IUserService
{
    Task<User> GetUserByIdAsync(int userId);
    Task CreateUserAsync(User user);
}

// 实现服务
public class UserService : BaseService, IUserService
{
    // 可以注入依赖项
    private readonly IRepository<User> _userRepository;
    
    public UserService(IRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }
    
    public async Task<User> GetUserByIdAsync(int userId)
    {
        // 服务实现
        return await _userRepository.FindByIdAsync(userId);
    }
    
    public async Task CreateUserAsync(User user)
    {
        // 服务实现
        await _userRepository.InsertAsync(user);
    }
}

// 注册服务到DI容器
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IUserService, UserService>();
    // 其他服务注册...
}

// 在控制器或其他组件中使用服务
public class UserController : Controller
{
    private readonly IUserService _userService;
    
    public UserController(IUserService userService)
    {
        _userService = userService;
    }
    
    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id)
    {
        var user = await _userService.GetUserByIdAsync(id);
        return Ok(user);
    }
}

2. 创建和配置后台任务

2.1 基本后台任务
// 定义后台任务
public class CleanupJob : BaseJobService
{
    protected override string JobName => "数据清理任务";
    
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Logger.Info($"[{JobName}] 开始执行");
        
        try
        {
            // 执行实际的清理逻辑
            await CleanupOldDataAsync();
            
            Logger.Info($"[{JobName}] 执行完成");
        }
        catch (Exception ex)
        {
            Logger.Error($"[{JobName}] 执行出错: {ex.Message}", ex);
        }
    }
    
    private async Task CleanupOldDataAsync()
    {
        // 清理逻辑实现
        // 例如删除超过90天的日志数据
    }
}

// 注册后台任务到Host
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            // 注册后台任务
            services.AddHostedService<CleanupJob>();
            // 其他服务注册...
        });
2.2 定时后台任务
public class ScheduleTask : BaseJobService
{
    private readonly PeriodicTimer _timer;
    private readonly TimeSpan _interval;
    
    protected override string JobName => "定时同步任务";
    
    public ScheduleTask()
    {
        // 设置定时间隔(每小时执行一次)
        _interval = TimeSpan.FromHours(1);
        _timer = new PeriodicTimer(_interval);
    }
    
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Logger.Info($"[{JobName}] 启动,间隔: {_interval.TotalHours}小时");
        
        while (!stoppingToken.IsCancellationRequested && 
               await _timer.WaitForNextTickAsync(stoppingToken))
        {
            try
            {
                Logger.Info($"[{JobName}] 开始执行");
                
                // 执行定时任务逻辑
                await SyncDataAsync();
                
                Logger.Info($"[{JobName}] 执行完成");
            }
            catch (Exception ex)
            {
                Logger.Error($"[{JobName}] 执行出错: {ex.Message}", ex);
            }
        }
    }
    
    private async Task SyncDataAsync()
    {
        // 同步数据逻辑实现
    }
}
2.3 父子任务模式
// 子任务实现
public class EmailSendSubJob : BaseSubJobService
{
    private readonly string _emailAddress;
    private readonly string _subject;
    private readonly string _body;
    
    public EmailSendSubJob(string emailAddress, string subject, string body)
    {
        _emailAddress = emailAddress;
        _subject = subject;
        _body = body;
    }
    
    protected override string JobName => $"发送邮件到 {_emailAddress}";
    
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Logger.Info($"[{JobName}] 开始执行");
        
        try
        {
            // 实际发送邮件的逻辑
            await SendEmailAsync();
            
            Logger.Info($"[{JobName}] 执行完成");
            
            // 标记子任务完成
            JobState = JobState.Completed;
        }
        catch (Exception ex)
        {
            Logger.Error($"[{JobName}] 执行出错: {ex.Message}", ex);
            
            // 标记子任务失败
            JobState = JobState.Failed;
            ErrorMessage = ex.Message;
        }
    }
    
    private async Task SendEmailAsync()
    {
        // 发送邮件实现
    }
}

// 父任务实现
public class BatchEmailJob : ParentJobService
{
    protected override string JobName => "批量发送邮件任务";
    
    public async Task StartBatchEmailAsync(List<(string email, string subject, string body)> emails)
    {
        Logger.Info($"[{JobName}] 开始处理,总邮件数: {emails.Count}");
        
        // 创建子任务列表
        var subJobs = emails.Select(e => 
            new EmailSendSubJob(e.email, e.subject, e.body)).ToList();
        
        // 添加子任务并启动
        AddSubJobs(subJobs);
        
        // 等待所有子任务完成
        await WaitForAllSubJobsAsync();
        
        // 汇总结果
        var completed = subJobs.Count(j => j.JobState == JobState.Completed);
        var failed = subJobs.Count(j => j.JobState == JobState.Failed);
        
        Logger.Info($"[{JobName}] 处理完成,成功: {completed}, 失败: {failed}");
    }
}

// 使用父子任务
public class EmailService : BaseService
{
    private readonly BatchEmailJob _batchEmailJob;
    
    public EmailService(BatchEmailJob batchEmailJob)
    {
        _batchEmailJob = batchEmailJob;
    }
    
    public async Task SendBatchEmailsAsync(List<(string email, string subject, string body)> emails)
    {
        await _batchEmailJob.StartBatchEmailAsync(emails);
    }
}

使用注意事项

  1. 服务命名和日志

    • 所有继承自BaseService或BaseJobService的类,应当设置有意义的JobName或类名,便于日志跟踪
    • 确保在关键操作点添加适当的日志记录
  2. 异常处理

    • 在服务实现中捕获并处理异常,避免将未处理的异常传播到上层
    • 对于后台任务,特别注意异常处理,确保任务不会因为异常而意外终止
  3. 资源释放

    • 在长时间运行的后台任务中,确保适当释放资源,特别是数据库连接和文件句柄
    • 当任务被取消时,及时清理资源
  4. 并发控制

    • 对于可能被多个实例同时执行的任务,实现必要的分布式锁或任务调度机制
    • 避免多个任务实例同时修改同一数据
  5. 任务监控

    • 实现任务状态监控机制,及时发现任务执行异常
    • 对于关键任务,考虑添加告警机制
  6. 依赖注入

    • 确保所有服务依赖通过构造函数注入,便于测试和维护
    • 避免在服务内部直接实例化其他服务,应通过依赖注入获取
  7. 性能考虑

    • 对于频繁执行的任务,注意控制资源使用,避免系统过载
    • 考虑使用批处理和异步操作提高任务执行效率
  8. 服务生命周期

    • 了解并正确使用不同的服务生命周期(Singleton、Scoped、Transient)
    • 避免在Singleton服务中注入Scoped依赖
  9. 配置外部化

    • 将任务执行参数、定时间隔等配置信息外部化,便于运行时调整
    • 考虑使用配置中心动态更新任务配置
  10. 测试策略

    • 为服务层编写单元测试,确保业务逻辑正确
    • 使用模拟对象(Mock)隔离服务依赖,提高测试效率
    • 考虑为关键任务编写集成测试,验证端到端功能

贡献者

  • yswenli

许可证

保留所有权利

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.1.7.1 183 1/7/2026
2025.12.23.1 258 12/23/2025
2025.12.16.1 348 12/16/2025
2025.12.15.2 294 12/15/2025
2025.12.15.1 325 12/15/2025
2025.12.12.1 217 12/12/2025
2025.12.11.1 506 12/11/2025
2025.12.4.1 271 12/4/2025
2025.12.3.3 747 12/3/2025
2025.12.3.2 735 12/3/2025
2025.12.3.1 745 12/3/2025
2025.12.2.1 757 12/2/2025
2025.11.28.1 250 11/28/2025
2025.11.25.1 274 11/25/2025
2025.11.21.1 470 11/21/2025
2025.11.20.1 469 11/20/2025
2025.11.19.2 487 11/19/2025
2025.11.19.1 501 11/19/2025
2025.11.18.2 495 11/18/2025
2025.11.18.1 479 11/18/2025
Loading failed

企服版框架中服务处理相关,包括常规Service的集成处理和后台任务JobService的处理