Domiyi.Toolkit 1.0.4

dotnet add package Domiyi.Toolkit --version 1.0.4
                    
NuGet\Install-Package Domiyi.Toolkit -Version 1.0.4
                    
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="Domiyi.Toolkit" Version="1.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Domiyi.Toolkit" Version="1.0.4" />
                    
Directory.Packages.props
<PackageReference Include="Domiyi.Toolkit" />
                    
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 Domiyi.Toolkit --version 1.0.4
                    
#r "nuget: Domiyi.Toolkit, 1.0.4"
                    
#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 Domiyi.Toolkit@1.0.4
                    
#: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=Domiyi.Toolkit&version=1.0.4
                    
Install as a Cake Addin
#tool nuget:?package=Domiyi.Toolkit&version=1.0.4
                    
Install as a Cake Tool

Domiyi.Toolkit

常用 .NET 工具组件库,提供 TTL 缓存、双端队列、后台轮询 Worker、对接第三方 HTTP 接口的 JSON 转换器,以及字符串/数值/集合扩展方法。

安装

dotnet add package Domiyi.Toolkit

目标框架: .NET 10

依赖: Microsoft.Extensions.Hosting.Abstractions(LoopWorker 使用)

主要组件

组件 命名空间 说明
ITtlCache / TtlCache Domiyi.Toolkit 线程安全的绝对过期(TTL)缓存
LoopWorker Domiyi.Toolkit 可托管的后台轮询基类(FixedDelay / FixedRate)
Deque<T> Domiyi.Toolkit.Collections 环形缓冲区实现的双端队列
CollectionExtensions Domiyi.Toolkit.Collections 集合判空、列表交集检测等
StringExtensions Domiyi.Toolkit.Extensions 按固定长度或分段长度切分字符串
NumericExtensions Domiyi.Toolkit.Extensions 整型按位读取(GetBit / IsBitSet)
LenientNumberJsonConverter<T> Domiyi.Toolkit.Json 数字:null / 空串 / 空白串 → 零,支持字符串数字
LenientStringJsonConverter Domiyi.Toolkit.Json 字符串:反序列化时 null → ""
LenientBoolJsonConverter Domiyi.Toolkit.Json 布尔:兼容 null / 字符串 / 数字
DateTimeJsonConverter Domiyi.Toolkit.Json DateTime:Unix 毫秒戳或自定义格式字符串
DateTimeOffsetJsonConverter Domiyi.Toolkit.Json DateTimeOffset:同上

使用示例

JSON 转换器(对接第三方接口)

第三方 API 常把 null、空串、字符串数字等脏数据塞进 JSON 字段。注册以下转换器后,System.Text.Json 反序列化时自动归一化,避免 NullReferenceException 或类型不匹配。

using System.Text.Json;
using Domiyi.Toolkit.Json;

var options = new JsonSerializerOptions
{
    Converters =
    {
        new LenientStringJsonConverter(),
        new LenientBoolJsonConverter(),
        new LenientNumberJsonConverter<int>(),
        new LenientNumberJsonConverter<long>(),
        new LenientNumberJsonConverter<decimal>(),
        new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"),
        new DateTimeOffsetJsonConverter("yyyy-MM-dd HH:mm:ss")
    }
};

// null → 0 / "" / false;字符串数字 "123" → 123
var dto = JsonSerializer.Deserialize<ThirdPartyDto>(json, options);
转换器 读取行为
LenientNumberJsonConverter<T> null、空串、纯空白串 → T.Zero;"123" → 数字;脏数据仍抛 JsonException
LenientStringJsonConverter null → ""(仅反序列化;序列化时 C# null 仍写 JSON null)
LenientBoolJsonConverter null / false / "0" / 0 → false;true / "1" / "true" / 1 → true
DateTimeJsonConverter 数字 → Unix 毫秒戳;字符串 → 指定格式(默认 yyyy-MM-dd HH:mm:ss)

LenientNumberJsonConverter<T> 约束为 INumberBase<T>,按需注册 int、long、decimal 等类型即可。大 payload 建议用 DeserializeAsync(stream) 直接从 HTTP 流反序列化,避免中间 string 分配。

TTL 缓存

using Domiyi.Toolkit;

var cache = new TtlCache<string, string>();

cache.Set("alice", "Alice", TimeSpan.FromMinutes(5));
cache.Set("bob", "Bob"); // 永不过期,需显式 Remove

if (cache.TryGet("alice", out var name))
    Console.WriteLine(name);

// 缓存 miss 时调用 factory 写入;ttl 为 null 时永不过期
var user = cache.GetOrCreate("carol", () => LoadUser("carol"), TimeSpan.FromMinutes(5));
var profile = await cache.GetOrCreateAsync("dave", () => LoadUserAsync("dave"), TimeSpan.FromMinutes(5));

foreach (var (key, value) in cache)
    Console.WriteLine($"{key}: {value}");

var snapshot = cache.Snapshot(); // 某一瞬间的一致快照

过期清理: 已过期条目在 TryGet 时惰性移除;其余过期条目由读写操作触发的后台扫描清理(默认间隔 1 分钟,对齐 MemoryCache 语义)。缓存长时间无访问时,可手动调用 Cleanup() 释放内存。

// 自定义后台扫描间隔;TimeSpan.Zero 禁用操作触发的后台扫描
var cache = new TtlCache<string, byte[]>(expirationScanFrequency: TimeSpan.FromSeconds(30));

cache.Cleanup(); // 主动移除所有已过期条目

自定义轮询 Worker

using Domiyi.Toolkit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public sealed class HeartbeatWorker(
    ILoggerFactory loggerFactory,
    IHostApplicationLifetime applicationLifetime) : LoopWorker(
    loggerFactory,
    new LoopOptions
    {
        Name = "Heartbeat",
        StartAfterApplicationStarted = true,
        InitDelayMs = 1_000,
        FixedDelayMs = 30_000
    },
    applicationLifetime)
{
    protected override Task ExecuteAsync(CancellationToken cancellationToken)
    {
        // 单次异常不会终止循环;可通过 WakeUp() 立即触发下一轮
        return Task.CompletedTask;
    }
}

// builder.Services.AddHostedService<HeartbeatWorker>();

双端队列

using Domiyi.Toolkit.Collections;

var deque = new Deque<int>();
deque.AddLast(1);
deque.AddFirst(0);
deque.Enqueue(2);

Console.WriteLine(deque.Dequeue());   // 0
Console.WriteLine(deque.RemoveLast()); // 2

Deque<T> 非线程安全,多线程访问需外部同步。

扩展方法

using Domiyi.Toolkit.Extensions;
using Domiyi.Toolkit.Collections;

"abcdef".Split(2);           // ["ab", "cd", "ef"]
"  a  b  ".Split([2, 2], StringSplitOptions.TrimEntries);

((byte)0b1010).IsBitSet(1);  // true
((byte)0b1010).GetBit(0);    // 0

list.IsNullOrEmpty();

许可证

This repo is licensed under the AGPL-3.0-or-later license.

基于本库的网络服务若对外提供,须向用户提供对应源代码。

链接

Product 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. 
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
1.0.4 73 9/29/2026
1.0.3 205 8/2/2026
1.0.2 119 7/22/2026
1.0.1 117 7/6/2026