Community程式設計與開發github.com

Akka.Hosting 實體參與者模式

使用 Akka.Hosting - GenericChildPerEntityParent、訊息提取器、叢集分片抽象化、akka-reminders 和 ITimeProvider 來建構實體參與者的模式。同時支援本機測試和叢集生產模式。

Akka.Hosting 實體參與者模式 是什麼?

此技能提供了一套經過驗證的模式,用於在使用 Akka.Hosting 時建構實體參與者(Entity Actors)。其核心原則是抽象化執行模式,讓相同的參與者程式碼能無縫地在單元測試(使用 GenericChildPerEntityParent 模擬分片語意)和生產環境(使用 Akka.Cluster.Sharding 的 ShardRegion)中運作。它還整合了測試友好的時間處理(透過 ITimeProvider)、持久化的排程任務(透過 akka-reminders),以及可組合的 Akka.Hosting 擴充方法來簡化註冊流程。對於需要在不同部署場景中保持一致行為的 Akka.NET 開發者來說,這套模式能顯著減少重複程式碼,並提高測試覆蓋率,主要支援 Akka.NET 與 Akka.Hosting 生態系統。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/akka-hosting-actor-patterns

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Akka.Hosting 參與者模式

何時使用此技能

在以下情況使用此技能:

  • 建構代表領域物件(使用者、訂單、發票等)的實體參與者
  • 需要參與者同時在單元測試(無叢集)和生產環境(叢集分片)中運作
  • 使用 akka-reminders 設定排程任務
  • 使用 Akka.Hosting 擴充方法註冊參與者
  • 建立可重複使用的參與者設定模式

核心原則

  1. 執行模式抽象化 - 相同的參與者程式碼可在本機(測試)或叢集(生產)執行
  2. 用於本機的 GenericChildPerEntityParent - 在沒有叢集開銷的情況下模擬分片語意
  3. 用於路由的訊息提取器 - 重複使用 Akka.Cluster.Sharding 的 IMessageExtractor 介面
  4. Akka.Hosting 擴充方法 - 流暢的設定,具有良好的組合性
  5. 用於可測試性的 ITimeProvider - 使用 ActorSystem.Scheduler 代替 DateTime.Now

執行模式

定義一個列舉來控制參與者行為:

/// <summary>
/// 決定如何設定 Akka.NET
/// </summary>
public enum AkkaExecutionMode
{
    /// <summary>
    /// 純本機參與者系統 - 無遠端、無叢集。
    /// 使用 GenericChildPerEntityParent 代替 ShardRegion。
    /// 適用於單元測試和簡單場景。
    /// </summary>
    LocalTest,

    /// <summary>
    /// 完整的 ShardRegion 叢集。
    /// 用於整合測試和生產環境。
    /// </summary>
    Clustered
}

GenericChildPerEntityParent

一個輕量級父參與者,將訊息路由到子實體,模擬叢集分片語意而不需要叢集:

using Akka.Actor;
using Akka.Cluster.Sharding;

/// <summary>
/// 一個通用的「每個實體一個子參與者」父參與者。
/// </summary>
/// <remarks>
/// 重複使用 Akka.Cluster.Sharding 的 IMessageExtractor 以實現一致的路由。
/// 非常適合不需要叢集開銷的單元測試。
/// </remarks>
public sealed class GenericChildPerEntityParent : ReceiveActor
{
    public static Props CreateProps(
        IMessageExtractor extractor,
        Func<string, Props> propsFactory)
    {
        return Props.Create(() =>
            new GenericChildPerEntityParent(extractor, propsFactory));
    }

    private readonly IMessageExtractor _extractor;
    private readonly Func<string, Props> _propsFactory;

    public GenericChildPerEntityParent(
        IMessageExtractor extractor,
        Func<string, Props> propsFactory)
    {
        _extractor = extractor;
        _propsFactory = propsFactory;

        ReceiveAny(message =>
        {
            var entityId = _extractor.EntityId(message);
            if (entityId is null) return;

            // 取得現有子參與者或建立新的
            Context.Child(entityId)
                .GetOrElse(() => Context.ActorOf(_propsFactory(entityId), entityId))
                .Forward(_extractor.EntityMessage(message));
        });
    }
}

訊息提取器

建立實作 IMessageExtractor(來自 Akka.Cluster.Sharding)的提取器:

using Akka.Cluster.Sharding;

/// <summary>
/// 根據強型別 ID 將訊息路由到實體參與者。
/// </summary>
public sealed class OrderMessageExtractor : HashCodeMessageExtractor
{
    public const int DefaultShardCount = 40;

    public OrderMessageExtractor(int maxNumberOfShards = DefaultShardCount)
        : base(maxNumberOfShards)
    {
    }

    public override string? EntityId(object message)
    {
        return message switch
        {
            IWithOrderId msg => msg.OrderId.Value.ToString(),
            _ => null
        };
    }
}

// 定義一個針對特定實體的訊息介面
public interface IWithOrderId
{
    OrderId OrderId { get; }
}

// 使用強型別 ID
public readonly record struct OrderId(Guid Value)
{
    public static OrderId New() => new(Guid.NewGuid());
    public override string ToString() => Value.ToString();
}

Akka.Hosting 擴充方法

建立抽象化執行模式的擴充方法:

using Akka.Cluster.Hosting;
using Akka.Cluster.Sharding;
using Akka.Hosting;

public static class OrderActorHostingExtensions
{
    /// <summary>
    /// 新增 OrderActor,支援本機和叢集模式。
    /// </summary>
    public static AkkaConfigurationBuilder WithOrderActor(
        this AkkaConfigurationBuilder builder,
        AkkaExecutionMode executionMode = AkkaExecutionMode.Clustered,
        string? clusterRole = null)
    {
        if (executionMode == AkkaExecutionMode.LocalTest)
        {
            // 非叢集模式:使用 GenericChildPerEntityParent
            builder.WithActors((system, registry, resolver) =>
            {
                var parent = system.ActorOf(
                    GenericChildPerEntityParent.CreateProps(
                        new OrderMessageExtractor(),
                        entityId => resolver.Props<OrderActor>(entityId)),
                    "orders");

                registry.Register<OrderActor>(parent);
            });
        }
        else
        {
            // 叢集模式:使用 ShardRegion
            builder.WithShardRegion<OrderActor>(
                "orders",
                (system, registry, resolver) =>
                    entityId => resolver.Props<OrderActor>(entityId),
                new OrderMessageExtractor(),
                new ShardOptions
                {
                    StateStoreMode = StateStoreMode.DData,
                    Role = clusterRole
                });
        }

        return builder;
    }
}

組合多個參與者

建立一個便利的方法來註冊所有領域參與者:

public static class DomainActorHostingExtensions
{
    /// <summary>
    /// 新增所有訂單領域參與者,並支援分片。
    /// </summary>
    public static AkkaConfigurationBuilder WithOrderDomainActors(
        this AkkaConfigurationBuilder builder,
        AkkaExecutionMode executionMode = AkkaExecutionMode.Clustered,
        string? clusterRole = null)
    {
        return builder
            .WithOrderActor(executionMode, clusterRole)
            .WithPaymentActor(executionMode, clusterRole)
            .WithShipmentActor(executionMode, clusterRole)
            .WithNotificationActor(); // 單例,不需要分片
    }
}

使用 ITimeProvider 進行排程

將 ActorSystem 的 Scheduler 註冊為 ITimeProvider,用於可測試的基於時間的邏輯:

public static class SharedAkkaHostingExtensions
{
    public static IServiceCollection AddAkkaWithTimeProvider(
        this IServiceCollection services,
        Action<AkkaConfigurationBuilder, IServiceProvider> configure)
    {
        // 使用 ActorSystem 的 Scheduler 註冊 ITimeProvider
        services.AddSingleton<ITimeProvider>(sp =>
            sp.GetRequiredService<ActorSystem>().Scheduler);

        return services.ConfigureAkka((builder, sp) =>
        {
            configure(builder, sp);
        });
    }
}

// 在你的參與者中注入 ITimeProvider
public class SubscriptionActor : ReceiveActor
{
    private readonly ITimeProvider _timeProvider;

    public SubscriptionActor(ITimeProvider timeProvider)
    {
        _timeProvider = timeProvider;

        // 使用 _timeProvider.GetUtcNow() 代替 DateTime.UtcNow
        // 這允許測試控制時間
    }
}

Akka.Reminders 整合

對於需要在重新啟動後保持的持久性排程任務,請使用 akka-reminders:

using Akka.Reminders;
using Akka.Reminders.Sql;
using Akka.Reminders.Sql.Configuration;
using Akka.Reminders.Storage;

public static class ReminderHostingExtensions
{
    /// <summary>
    /// 使用 PostgreSQL 儲存設定 akka-reminders。
    /// </summary>
    public static AkkaConfigurationBuilder WithPostgresReminders(
        this AkkaConfigurationBuilder builder,
        string connectionString,
        string schemaName = "reminders",
        string tableName = "scheduled_reminders",
        bool autoInitialize = true)
    {
        return builder.WithLocalReminders(reminders => reminders
            .WithResolver(sys => new GenericChildPerEntityResolver(sys))
            .WithStorage(system =>
            {
                var settings = SqlReminderStorageSettings.CreatePostgreSql(
                    connectionString,
                    schemaName,
                    tableName,
                    autoInitialize);
                return new SqlReminderStorage(settings, system);
            })
            .WithSettings(new ReminderSettings
            {
                MaxSlippage = TimeSpan.FromSeconds(30),
                MaxDeliveryAttempts = 3,
                RetryBackoffBase = TimeSpan.FromSeconds(10)
            }));
    }

    /// <summary>
    /// 使用記憶體儲存設定 akka-reminders 用於測試。
    /// </summary>
    public static AkkaConfigurationBuilder WithInMemoryReminders(
        this AkkaConfigurationBuilder builder)
    {
        return builder.WithLocalReminders(reminders => reminders
            .WithResolver(sys => new GenericChildPerEntityResolver(sys))
            .WithStorage(system => new InMemoryReminderStorage())
            .WithSettings(new ReminderSettings
            {
                MaxSlippage = TimeSpan.FromSeconds(1),
                MaxDeliveryAttempts = 3,
                RetryBackoffBase = TimeSpan.FromMilliseconds(100)
            }));
    }
}

用於 Child-Per-Entity 的自訂提醒解析器

將提醒回呼路由到 GenericChildPerEntityParent 參與者:

using Akka.Actor;
using Akka.Hosting;
using Akka.Reminders;

/// <summary>
/// 將提醒目標解析為 GenericChildPerEntityParent 參與者。
/// </summary>
public sealed class GenericChildPerEntityResolver : IReminderActorResolver
{
    private readonly ActorSystem _system;

    public GenericChildPerEntityResolver(ActorSystem system)
    {
        _system = system;
    }

    public IActorRef ResolveActorRef(ReminderEntry entry)
    {
        var registry = ActorRegistry.For(_system);

        return entry.Key switch
        {
            var k when k.StartsWith("order-") =>
                registry.Get<OrderActor>(),
            var k when k.StartsWith("subscription-") =>
                registry.Get<SubscriptionActor>(),
            _ => throw new InvalidOperationException(
                $"未知的提醒金鑰格式:{entry.Key}")
        };
    }
}

單例參與者(不分片)

對於只需要一個實例的參與者:

public static AkkaConfigurationBuilder WithEmailSenderActor(
    this AkkaConfigurationBuilder builder)
{
    return builder.WithActors((system, registry, resolver) =>
    {
        var actor = system.ActorOf(
            resolver.Props<EmailSenderActor>(),
            "email-sender");
        registry.Register<EmailSenderActor>(actor);
    });
}

用於註冊表的標記類型

當你需要參考已註冊為父參與者的參與者時:

/// <summary>
/// ActorRegistry 的標記類型,用於取得訂單管理員
/// (OrderActor 的 GenericChildPerEntityParent)。
/// </summary>
public sealed class OrderManagerActor;

// 在擴充方法中使用
registry.Register<OrderManagerActor>(parent);

// 在控制器/服務中使用
public class OrderService
{
    private readonly IActorRef _orderManager;

    public OrderService(IRequiredActor<OrderManagerActor> orderManager)
    {
        _orderManager = orderManager.ActorRef;
    }

    public async Task<OrderResponse> CreateOrder(CreateOrderCommand cmd)
    {
        return await _orderManager.Ask<OrderResponse>(cmd);
    }
}

參與者中的 DI 範圍管理

參與者沒有自動的 DI 範圍。 與 ASP.NET 控制器不同(每個 HTTP 請求建立一個範圍),參與者是長期存在的。如果你需要範圍服務(如 DbContext),請注入 IServiceProvider 並手動建立範圍。

模式:每個訊息一個範圍

public sealed class OrderProcessingActor : ReceiveActor
{
    private readonly IServiceProvider _serviceProvider;
    private readonly IActorRef _notificationActor;

    public OrderProcessingActor(
        IServiceProvider serviceProvider,
        IRequiredActor<NotificationActor> notificationActor)
    {
        _serviceProvider = serviceProvider;
        _notificationActor = notificationActor.ActorRef;

        ReceiveAsync<ProcessOrder>(HandleProcessOrder);
    }

    private async Task HandleProcessOrder(ProcessOrder msg)
    {
        // 為此訊息建立範圍 - 處理後會釋放
        using var scope = _serviceProvider.CreateScope();

        // 在範圍內解析範圍服務
        var orderRepository = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
        var paymentService = scope.ServiceProvider.GetRequiredService<IPaymentService>();
        var emailComposer = scope.ServiceProvider.GetRequiredService<IOrderEmailComposer>();

        // 使用範圍服務執行工作
        var order = await orderRepository.GetByIdAsync(msg.OrderId);
        var payment = await paymentService.ProcessAsync(order);

        // 範圍釋放時 DbContext 變更會提交
    }
}

為什麼使用此模式

效益說明
每個訊息都有全新的 DbContext避免訊息之間的過時實體追蹤
適當的釋放每個訊息處理完後釋放資料庫連線
隔離性一個訊息的錯誤不會破壞另一個訊息的狀態
可測試性可以在測試中注入 Mock 的 IServiceProvider

單例服務 - 直接注入

對於無狀態、執行緒安全的服務,直接注入(不需要範圍):

public sealed class NotificationActor : ReceiveActor
{
    private readonly IEmailLinkGenerator _linkGenerator;  // 單例 - 沒問題!
    private readonly IMjmlTemplateRenderer _renderer;     // 單例 - 沒問題!

    public NotificationActor(
        IEmailLinkGenerator linkGenerator,
        IMjmlTemplateRenderer renderer)
    {
        _linkGenerator = linkGenerator;
        _renderer = renderer;
    }
}

摘要:DI 與參與者的最佳實踐

服務生命週期注入方式範例
單例(跨所有訊息共享)直接注入到建構函式ILogger<T>, IHttpClientFactory, IMapper
範圍(每個訊息新的)注入 IServiceProvider 並建立範圍ApplicationDbContext, IOrderRepository
暫時(每次解析時新建)通過範圍注入 IServiceProvider 或直接注入IOptionsSnapshot<T>, 輕量計算服務

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能