Getting started with the Dapr actor .NET SDK

Try out .NET virtual actors with this example

Prerequisites

Overview

This document describes how to create an Actor(MyActor) and invoke its methods on the client application.

  1. MyActor --- MyActor.Interfaces
  2. |
  3. +- MyActorService
  4. |
  5. +- MyActorClient
  • The interface project(\MyActor\MyActor.Interfaces). This project contains the interface definition for the actor. Actor interfaces can be defined in any project with any name. The interface defines the actor contract that is shared by the actor implementation and the clients calling the actor. Because client projects may depend on it, it typically makes sense to define it in an assembly that is separate from the actor implementation.

  • The actor service project(\MyActor\MyActorService). This project implements ASP.Net Core web service that is going to host the actor. It contains the implementation of the actor, MyActor.cs. An actor implementation is a class that derives from the base type Actor and implements the interfaces defined in the MyActor.Interfaces project. An actor class must also implement a constructor that accepts an ActorService instance and an ActorId and passes them to the base Actor class.

  • The actor client project(\MyActor\MyActorClient) This project contains the implementation of the actor client which calls MyActor’s method defined in Actor Interfaces.

STEP 1 - Create Actor Interface

Actor interface defines the actor contract that is shared by the actor implementation and the clients calling the actor.

Actor interface is defined with the below requirements:

  • Actor interface must inherit Dapr.Actors.IActor interface
  • The return type of Actor method must be Task or Task<object>
  • Actor method can have one argument at a maximum

Create project and add dependencies

  1. # Create Actor Interfaces
  2. dotnet new classlib -o MyActor.Interfaces
  3. cd MyActor.Interfaces
  4. # Add Dapr.Actors nuget package. Please use the latest package version from nuget.org
  5. dotnet add package Dapr.Actors -v 1.0.0-rc02

Implement IMyActor Interface

Define IMyActor Interface and MyData data object.

  1. using Dapr.Actors;
  2. using System.Threading.Tasks;
  3. namespace MyActor.Interfaces
  4. {
  5. public interface IMyActor : IActor
  6. {
  7. Task<string> SetDataAsync(MyData data);
  8. Task<MyData> GetDataAsync();
  9. Task RegisterReminder();
  10. Task UnregisterReminder();
  11. Task RegisterTimer();
  12. Task UnregisterTimer();
  13. }
  14. public class MyData
  15. {
  16. public string PropertyA { get; set; }
  17. public string PropertyB { get; set; }
  18. public override string ToString()
  19. {
  20. var propAValue = this.PropertyA == null ? "null" : this.PropertyA;
  21. var propBValue = this.PropertyB == null ? "null" : this.PropertyB;
  22. return $"PropertyA: {propAValue}, PropertyB: {propBValue}";
  23. }
  24. }
  25. }

STEP 2 - Create Actor Service

Dapr uses ASP.NET web service to host Actor service. This section will implement IMyActor actor interface and register Actor to Dapr Runtime.

Create project and add dependencies

  1. # Create ASP.Net Web service to host Dapr actor
  2. dotnet new webapi -o MyActorService
  3. cd MyActorService
  4. # Add Dapr.Actors nuget package. Please use the latest package version from nuget.org
  5. dotnet add package Dapr.Actors -v 1.0.0-rc02
  6. # Add Dapr.Actors.AspNetCore nuget package. Please use the latest package version from nuget.org
  7. dotnet add package Dapr.Actors.AspNetCore -v 1.0.0-rc02
  8. # Add Actor Interface reference
  9. dotnet add reference ../MyActor.Interfaces/MyActor.Interfaces.csproj

Add Actor implementation

Implement IMyActor interface and derive from Dapr.Actors.Actor class. Following example shows how to use Actor Reminders as well. For Actors to use Reminders, it must derive from IRemindable. If you don’t intend to use Reminder feature, you can skip implementing IRemindable and reminder specific methods which are shown in the code below.

  1. using Dapr.Actors;
  2. using Dapr.Actors.Runtime;
  3. using MyActor.Interfaces;
  4. using System;
  5. using System.Threading.Tasks;
  6. namespace MyActorService
  7. {
  8. internal class MyActor : Actor, IMyActor, IRemindable
  9. {
  10. // The constructor must accept ActorHost as a parameter, and can also accept additional
  11. // parameters that will be retrieved from the dependency injection container
  12. //
  13. /// <summary>
  14. /// Initializes a new instance of MyActor
  15. /// </summary>
  16. /// <param name="host">The Dapr.Actors.Runtime.ActorHost that will host this actor instance.</param>
  17. public MyActor(ActorHost host)
  18. : base(host)
  19. {
  20. }
  21. /// <summary>
  22. /// This method is called whenever an actor is activated.
  23. /// An actor is activated the first time any of its methods are invoked.
  24. /// </summary>
  25. protected override Task OnActivateAsync()
  26. {
  27. // Provides opportunity to perform some optional setup.
  28. Console.WriteLine($"Activating actor id: {this.Id}");
  29. return Task.CompletedTask;
  30. }
  31. /// <summary>
  32. /// This method is called whenever an actor is deactivated after a period of inactivity.
  33. /// </summary>
  34. protected override Task OnDeactivateAsync()
  35. {
  36. // Provides Opporunity to perform optional cleanup.
  37. Console.WriteLine($"Deactivating actor id: {this.Id}");
  38. return Task.CompletedTask;
  39. }
  40. /// <summary>
  41. /// Set MyData into actor's private state store
  42. /// </summary>
  43. /// <param name="data">the user-defined MyData which will be stored into state store as "my_data" state</param>
  44. public async Task<string> SetDataAsync(MyData data)
  45. {
  46. // Data is saved to configured state store implicitly after each method execution by Actor's runtime.
  47. // Data can also be saved explicitly by calling this.StateManager.SaveStateAsync();
  48. // State to be saved must be DataContract serializable.
  49. await this.StateManager.SetStateAsync<MyData>(
  50. "my_data", // state name
  51. data); // data saved for the named state "my_data"
  52. return "Success";
  53. }
  54. /// <summary>
  55. /// Get MyData from actor's private state store
  56. /// </summary>
  57. /// <return>the user-defined MyData which is stored into state store as "my_data" state</return>
  58. public Task<MyData> GetDataAsync()
  59. {
  60. // Gets state from the state store.
  61. return this.StateManager.GetStateAsync<MyData>("my_data");
  62. }
  63. /// <summary>
  64. /// Register MyReminder reminder with the actor
  65. /// </summary>
  66. public async Task RegisterReminder()
  67. {
  68. await this.RegisterReminderAsync(
  69. "MyReminder", // The name of the reminder
  70. null, // User state passed to IRemindable.ReceiveReminderAsync()
  71. TimeSpan.FromSeconds(5), // Time to delay before invoking the reminder for the first time
  72. TimeSpan.FromSeconds(5)); // Time interval between reminder invocations after the first invocation
  73. }
  74. /// <summary>
  75. /// Unregister MyReminder reminder with the actor
  76. /// </summary>
  77. public Task UnregisterReminder()
  78. {
  79. Console.WriteLine("Unregistering MyReminder...");
  80. return this.UnregisterReminderAsync("MyReminder");
  81. }
  82. // <summary>
  83. // Implement IRemindeable.ReceiveReminderAsync() which is call back invoked when an actor reminder is triggered.
  84. // </summary>
  85. public Task ReceiveReminderAsync(string reminderName, byte[] state, TimeSpan dueTime, TimeSpan period)
  86. {
  87. Console.WriteLine("ReceiveReminderAsync is called!");
  88. return Task.CompletedTask;
  89. }
  90. /// <summary>
  91. /// Register MyTimer timer with the actor
  92. /// </summary>
  93. public Task RegisterTimer()
  94. {
  95. return this.RegisterTimerAsync(
  96. "MyTimer", // The name of the timer
  97. nameof(this.OnTimerCallBack), // Timer callback
  98. null, // User state passed to OnTimerCallback()
  99. TimeSpan.FromSeconds(5), // Time to delay before the async callback is first invoked
  100. TimeSpan.FromSeconds(5)); // Time interval between invocations of the async callback
  101. }
  102. /// <summary>
  103. /// Unregister MyTimer timer with the actor
  104. /// </summary>
  105. public Task UnregisterTimer()
  106. {
  107. Console.WriteLine("Unregistering MyTimer...");
  108. return this.UnregisterTimerAsync("MyTimer");
  109. }
  110. /// <summary>
  111. /// Timer callback once timer is expired
  112. /// </summary>
  113. private Task OnTimerCallBack(byte[] data)
  114. {
  115. Console.WriteLine("OnTimerCallBack is called!");
  116. return Task.CompletedTask;
  117. }
  118. }
  119. }

Using an explicit actor type name

By default, the “type” of the actor as seen by clients is derived from the name of the actor implementation class. If desired, you can specify an explicit type name by attaching an ActorAttribute attribute to the actor implementation class.

  1. [Actor(TypeName = "MyCustomActorTypeName")]
  2. internal class MyActor : Actor, IMyActor
  3. {
  4. // ...
  5. }

Register Actor runtime with ASP.NET Core startup

The Actor runtime is configured through ASP.NET Core Startup.cs.

The runtime uses the ASP.NET Core dependency injection system to register actor types and essential services. This integration is provided through the AddActors(...) method call in ConfigureServices(...). Use the delegate passed to AddActors(...) to register actor types and configure actor runtime settings. You can register additional types for dependency injection inside ConfigureServices(...). These will be available to be injected into the constructors of your Actor types.

Actors are implemented via HTTP calls with the Dapr runtime. This functionality is part of the application’s HTTP processing pipeline and is registered inside UseEndpoints(...) inside Configure(...).

  1. // In Startup.cs
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4. // Register actor runtime with DI
  5. services.AddActors(options =>
  6. {
  7. // Register actor types and configure actor settings
  8. options.Actors.RegisterActor<MyActor>();
  9. });
  10. // Register additional services for use with actors
  11. services.AddSingleton<BankService>();
  12. }
  13. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  14. {
  15. if (env.IsDevelopment())
  16. {
  17. app.UseDeveloperExceptionPage();
  18. }
  19. else
  20. {
  21. app.UseHsts();
  22. }
  23. app.UseRouting();
  24. app.UseEndpoints(endpoints =>
  25. {
  26. // Register actors handlers that interface with the Dapr runtime.
  27. endpoints.MapActorsHandlers();
  28. });
  29. }

Optional - Override Default Actor Settings

Actor Settings are per app. The settings described here are available on the options and can be modified as below.

The following code extends the previous section to do this. Please note the values below are an example only.

  1. // In Startup.cs
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4. // Register actor runtime with DI
  5. services.AddActors(options =>
  6. {
  7. // Register actor types and configure actor settings
  8. options.Actors.RegisterActor<MyActor>();
  9. options.ActorIdleTimeout = TimeSpan.FromMinutes(10);
  10. options.ActorScanInterval = TimeSpan.FromSeconds(35);
  11. options.DrainOngoingCallTimeout = TimeSpan.FromSeconds(35);
  12. options.DrainRebalancedActors = true;
  13. });
  14. // Register additional services for use with actors
  15. services.AddSingleton<BankService>();
  16. }

STEP 3 - Add a client

Create a simple console app to call the actor service. Dapr SDK provides Actor Proxy client to invoke actor methods defined in Actor Interface.

Create project and add dependencies

  1. # Create Actor's Client
  2. dotnet new console -o MyActorClient
  3. cd MyActorClient
  4. # Add Dapr.Actors nuget package. Please use the latest package version from nuget.org
  5. dotnet add package Dapr.Actors -v 1.0.0-rc02
  6. # Add Actor Interface reference
  7. dotnet add reference ../MyActor.Interfaces/MyActor.Interfaces.csproj

Invoke Actor method with Actor Service Remoting

We recommend to use the local proxy to actor instance because ActorProxy.Create<IMyActor>(actorID, actorType) returns strongly-typed actor instance to set up the remote procedure call.

  1. namespace MyActorClient
  2. {
  3. using Dapr.Actors;
  4. using Dapr.Actors.Client;
  5. using MyActor.Interfaces;
  6. using System;
  7. using System.Threading.Tasks;
  8. ...
  9. static async Task InvokeActorMethodWithRemotingAsync()
  10. {
  11. var actorType = "MyActor"; // Registered Actor Type in Actor Service
  12. var actorID = new ActorId("1");
  13. // Create the local proxy by using the same interface that the service implements
  14. // By using this proxy, you can call strongly typed methods on the interface using Remoting.
  15. var proxy = ActorProxy.Create<IMyActor>(actorID, actorType);
  16. var response = await proxy.SetDataAsync(new MyData()
  17. {
  18. PropertyA = "ValueA",
  19. PropertyB = "ValueB",
  20. });
  21. Console.WriteLine(response);
  22. var savedData = await proxy.GetDataAsync();
  23. Console.WriteLine(savedData);
  24. }
  25. ...
  26. }

Invoke Actor method without Actor Service Remoting

You can invoke Actor methods without remoting (directly over http or using helper methods provided in ActorProxy), if Actor method accepts at-most one argument. Actor runtime will deserialize the incoming request body from client and use it as method argument to invoke the actor method. When making non-remoting calls Actor method arguments and return types are serialized, deserialized as JSON.

ActorProxy.Create(actorID, actorType) returns ActorProxy instance and allow to use the raw http client to invoke the method defined in IMyActor.

  1. namespace MyActorClient
  2. {
  3. using Dapr.Actors;
  4. using Dapr.Actors.Client;
  5. using MyActor.Interfaces;
  6. using System;
  7. using System.Threading.Tasks;
  8. ...
  9. static async Task InvokeActorMethodWithoutRemotingAsync()
  10. {
  11. var actorType = "MyActor";
  12. var actorID = new ActorId("1");
  13. // Create Actor Proxy instance to invoke the methods defined in the interface
  14. var proxy = ActorProxy.Create(actorID, actorType);
  15. // Need to specify the method name and response type explicitly
  16. var response = await proxy.InvokeMethodAsync<MyData, string>("SetDataAsync", new MyData()
  17. {
  18. PropertyA = "ValueA",
  19. PropertyB = "ValueB",
  20. });
  21. Console.WriteLine(response);
  22. var savedData = await proxy.InvokeMethodAsync<MyData>("GetDataAsync");
  23. Console.WriteLine(savedData);
  24. }
  25. ...
  26. }

Run Actor

In order to validate and debug actor service and client, we need to run actor services via Dapr CLI first.

  1. Run Dapr Runtime via Dapr cli

    1. $ dapr run --app-id myapp --app-port 5000 --dapr-http-port 3500 dotnet run

    After executing MyActorService via Dapr runtime, make sure that application is discovered on port 5000 and actor connection is established successfully.

    1. INFO[0000] starting Dapr Runtime -- version -- commit
    2. INFO[0000] log level set to: info
    3. INFO[0000] standalone mode configured
    4. INFO[0000] dapr id: myapp
    5. INFO[0000] loaded component statestore (state.redis)
    6. INFO[0000] application protocol: http. waiting on port 5000
    7. INFO[0000] application discovered on port 5000
    8. INFO[0000] application configuration loaded
    9. 2019/08/27 14:42:06 redis: connecting to localhost:6379
    10. 2019/08/27 14:42:06 redis: connected to localhost:6379 (localAddr: [::1]:53155, remAddr: [::1]:6379)
    11. INFO[0000] actor runtime started. actor idle timeout: 1h0m0s. actor scan interval: 30s
    12. INFO[0000] actors: starting connection attempt to placement service at localhost:50005
    13. INFO[0000] http server is running on port 3500
    14. INFO[0000] gRPC server is running on port 50001
    15. INFO[0000] dapr initialized. Status: Running. Init Elapsed 19.699438ms
    16. INFO[0000] actors: established connection to placement service at localhost:50005
    17. INFO[0000] actors: placement order received: lock
    18. INFO[0000] actors: placement order received: update
    19. INFO[0000] actors: placement tables updated
    20. INFO[0000] actors: placement order received: unlock
    21. ...
  2. Run MyActorClient

    MyActorClient will console out if it calls actor hosted in MyActorService successfully.

    If you specify the different Dapr runtime http port (default port: 3500), you need to set DAPR_HTTP_PORT environment variable before running the client.

    1. Success
    2. PropertyA: ValueA, PropertyB: ValueB

Last modified January 1, 0001