T2FGame.Core
1.0.9
dotnet add package T2FGame.Core --version 1.0.9
NuGet\Install-Package T2FGame.Core -Version 1.0.9
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="T2FGame.Core" Version="1.0.9" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="T2FGame.Core" Version="1.0.9" />
<PackageReference Include="T2FGame.Core" />
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 T2FGame.Core --version 1.0.9
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: T2FGame.Core, 1.0.9"
#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 T2FGame.Core@1.0.9
#: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=T2FGame.Core&version=1.0.9
#tool nuget:?package=T2FGame.Core&version=1.0.9
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
T2FGame.Core
T2FGame 框架的核心库,提供 DDD 构建块、Result 模式、领域事件等基础设施。
功能特性
- DDD 构建块:Entity、AggregateRoot、ValueObject、Repository 接口
- Result 模式:函数式错误处理,避免异常滥用
- 领域事件:事件定义、事件总线、事件处理器
- 领域事件分发器:AggregateRoot 与 EventBus 集成
安装
<PackageReference Include="T2FGame.Core" />
核心组件
1. DDD 构建块
Entity(实体)
public class Player : Entity<long>
{
public string Name { get; private set; }
public int Level { get; private set; }
public Player(long id, string name) : base(id)
{
Name = name;
Level = 1;
}
public void LevelUp()
{
Level++;
}
}
AggregateRoot(聚合根)
public class Order : AggregateRoot<Guid>
{
public long UserId { get; private set; }
public OrderStatus Status { get; private set; }
private readonly List<OrderItem> _items = new();
public Order(Guid id, long userId) : base(id)
{
UserId = userId;
Status = OrderStatus.Created;
// 添加领域事件
AddDomainEvent(new OrderCreatedEvent(id, userId));
}
public void Complete()
{
Status = OrderStatus.Completed;
AddDomainEvent(new OrderCompletedEvent(Id));
}
}
ValueObject(值对象)
public class Money : ValueObject
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Amount;
yield return Currency;
}
}
2. Result 模式
基本用法
// 成功结果
Result<Player> success = Result.Success(player);
// 失败结果
Result<Player> failure = Result.Failure<Player>(
Error.NotFound("Player.NotFound", "玩家不存在"));
// 链式调用
var result = await GetPlayerAsync(playerId)
.Bind(player => ValidatePlayer(player))
.Map(player => player.ToDto())
.Match(
onSuccess: dto => Ok(dto),
onFailure: error => BadRequest(error.Message)
);
预定义错误
// 验证错误
Error.Validation("Field.Invalid", "字段格式不正确");
// 未找到错误
Error.NotFound("Entity.NotFound", "实体不存在");
// 冲突错误
Error.Conflict("Entity.Conflict", "实体已存在");
// 未授权错误
Error.Unauthorized("Auth.Failed", "认证失败");
3. 领域事件
定义事件
public record PlayerCreatedEvent(long PlayerId, string Name) : IDomainEvent
{
public Guid EventId { get; } = Guid.NewGuid();
public DateTime OccurredOn { get; } = DateTime.UtcNow;
}
事件处理器
public class PlayerCreatedHandler : IEventHandler<PlayerCreatedEvent>
{
public async Task HandleAsync(PlayerCreatedEvent @event, CancellationToken cancellationToken)
{
// 处理事件逻辑
Console.WriteLine($"玩家 {@event.Name} 已创建");
}
}
事件发布
public class PlayerService
{
private readonly IEventBus _eventBus;
public async Task CreatePlayerAsync(string name)
{
var player = new Player(name);
// 发布事件(等待处理完成)
await _eventBus.PublishAsync(new PlayerCreatedEvent(player.Id, name));
// 或者 Fire-and-Forget
_eventBus.PublishFireAndForget(new PlayerCreatedEvent(player.Id, name));
}
}
4. Repository 接口
// 通用仓储接口
public interface IRepository<TEntity, TId>
{
Task<TEntity?> GetByIdAsync(TId id, CancellationToken cancellationToken = default);
Task<IReadOnlyList<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate, ...);
Task<TEntity> AddAsync(TEntity entity, CancellationToken cancellationToken = default);
Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default);
Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default);
}
// 聚合根仓储接口(支持领域事件分发)
public interface IAggregateRepository<TAggregate, TId> : IRepository<TAggregate, TId>
{
Task SaveAsync(TAggregate aggregate, CancellationToken cancellationToken = default);
}
依赖注入
services.AddSingleton<IEventBus, InMemoryEventBus>();
services.AddSingleton<IDomainEventDispatcher, DomainEventDispatcher>();
// 注册事件处理器
services.AddTransient<IEventHandler<PlayerCreatedEvent>, PlayerCreatedHandler>();
目录结构
T2FGame.Core/
├── DDD/
│ ├── Entity.cs # 实体基类
│ ├── AggregateRoot.cs # 聚合根基类
│ ├── ValueObject.cs # 值对象基类
│ ├── IRepository.cs # 仓储接口
│ ├── IDomainEventDispatcher.cs # 领域事件分发器接口
│ └── DomainEventDispatcher.cs # 领域事件分发器实现
├── Events/
│ ├── IDomainEvent.cs # 领域事件接口
│ ├── IEventBus.cs # 事件总线接口
│ ├── IEventHandler.cs # 事件处理器接口
│ └── InMemoryEventBus.cs # 内存事件总线实现
└── Results/
├── Result.cs # Result 类型
├── Error.cs # 错误类型
└── ResultExtensions.cs # 扩展方法
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. 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.
-
net9.0
NuGet packages (4)
Showing the top 4 NuGet packages that depend on T2FGame.Core:
| Package | Downloads |
|---|---|
|
T2FGame
T2FGame Framework - A high-performance distributed game server framework inspired by ioGame. This meta-package includes all T2FGame components. |
|
|
T2FGame.Action
T2FGame Framework - Action framework for message routing and handling, inspired by ioGame |
|
|
T2FGame.Persistence.MongoDB
T2FGame Framework - MongoDB persistence implementation |
|
|
T2FGame.Room
T2FGame Framework - Game room framework for multiplayer games, inspired by ioGame's RoomKit |
GitHub repositories
This package is not used by any popular GitHub repositories.