How to: Run and use virtual actors in the .NET SDK

    The Dapr actor package allows you to interact with Dapr virtual actors from a .NET application. In this guide, you learn how to:

    • Create an Actor ().
    • Invoke its methods on the client application.

    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 shared by:

    • The actor implementation
    • The clients calling the actor

    Because client projects may depend on it, it’s better to define it in an assembly separate from the actor implementation.

    The actor service project (\MyActor\MyActorService)

    This project implements the ASP.Net Core web service that hosts the actor. It contains the implementation of the actor, MyActor.cs. An actor implementation is a class that:

    • Derives from the base type Actor
    • 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 0: Prepare

    Since we’ll be creating 3 projects, choose an empty directory to start from, and open it in your terminal of choice.

    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
    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
    6. cd ..

    Implement IMyActor interface

    Define IMyActor interface and MyData data object. Paste the following code into MyActor.cs in the MyActor.Interfaces project.

    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.

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

    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.

    Paste the following code into MyActor.cs in the MyActorService project:

    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 inside Configure(...).

    Paste the following code into Startup.cs in the MyActorService project:

    1. using Microsoft.AspNetCore.Builder;
    2. using Microsoft.AspNetCore.Hosting;
    3. using Microsoft.Extensions.DependencyInjection;
    4. using Microsoft.Extensions.Hosting;
    5. namespace MyActorService
    6. {
    7. public class Startup
    8. {
    9. public void ConfigureServices(IServiceCollection services)
    10. {
    11. services.AddActors(options =>
    12. {
    13. // Register actor types and configure actor settings
    14. options.Actors.RegisterActor<MyActor>();
    15. });
    16. }
    17. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    18. {
    19. if (env.IsDevelopment())
    20. {
    21. app.UseDeveloperExceptionPage();
    22. }
    23. else
    24. {
    25. // By default, ASP.Net Core uses port 5000 for HTTP. The HTTP
    26. // redirection will interfere with the Dapr runtime. You can
    27. // move this out of the else block if you use port 5001 in this
    28. // example, and developer tooling (such as the VSCode extension).
    29. app.UseHttpsRedirection();
    30. }
    31. app.UseRouting();
    32. app.UseEndpoints(endpoints =>
    33. {
    34. // Register actors handlers that interface with the Dapr runtime.
    35. endpoints.MapActorsHandlers();
    36. });
    37. }
    38. }
    39. }

    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 actor client 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
    6. # Add Actor Interface reference
    7. dotnet add reference ../MyActor.Interfaces/MyActor.Interfaces.csproj
    8. cd ..

    Paste the following code into Program.cs in the MyActorClient project:

    1. using System;
    2. using System.Threading.Tasks;
    3. using Dapr.Actors;
    4. using Dapr.Actors.Client;
    5. using MyActor.Interfaces;
    6. namespace MyActorClient
    7. {
    8. {
    9. static async Task MainAsync(string[] args)
    10. {
    11. Console.WriteLine("Startup up...");
    12. // Registered Actor Type in Actor Service
    13. var actorType = "MyActor";
    14. // An ActorId uniquely identifies an actor instance
    15. // If the actor matching this id does not exist, it will be created
    16. var actorId = new ActorId("1");
    17. // Create the local proxy by using the same interface that the service implements.
    18. //
    19. // You need to provide the type and id so the actor can be located.
    20. var proxy = ActorProxy.Create<IMyActor>(actorId, actorType);
    21. // Now you can use the actor interface to call the actor's methods.
    22. Console.WriteLine($"Calling SetDataAsync on {actorType}:{actorId}...");
    23. var response = await proxy.SetDataAsync(new MyData()
    24. {
    25. PropertyA = "ValueA",
    26. PropertyB = "ValueB",
    27. });
    28. Console.WriteLine($"Got response: {response}");
    29. Console.WriteLine($"Calling GetDataAsync on {actorType}:{actorId}...");
    30. var savedData = await proxy.GetDataAsync();
    31. Console.WriteLine($"Got response: {response}");
    32. }
    33. }
    34. }

    Running the code

    The projects that you’ve created can now to test the sample.

    1. Run MyActorService

      Since MyActorService is hosting actors, it needs to be run with the Dapr CLI.

      You will see commandline output from both daprd and MyActorService in this terminal. You should see something like the following, which indicates that the application started successfully.

      1. ...
      2. ℹ️ Updating metadata for app command: dotnet run
      3. You're up and running! Both Dapr and your app logs will appear here.
      4. == APP == info: Microsoft.Hosting.Lifetime[0]
      5. == APP == Now listening on: https://localhost:5001
      6. == APP == info: Microsoft.Hosting.Lifetime[0]
      7. == APP == Now listening on: http://localhost:5000
      8. == APP == info: Microsoft.Hosting.Lifetime[0]
      9. == APP == Application started. Press Ctrl+C to shut down.
      10. == APP == info: Microsoft.Hosting.Lifetime[0]
      11. == APP == Hosting environment: Development
      12. == APP == info: Microsoft.Hosting.Lifetime[0]
      13. == APP == Content root path: /Users/ryan/actortest/MyActorService
    2. Run MyActorClient

      MyActorClient is acting as the client, and it can be run normally with dotnet run.

      Open a new terminal an navigate to the MyActorClient directory. Then run the project with:

      1. dotnet run

      You should see commandline output like:

      1. Startup up...
      2. Calling SetDataAsync on MyActor:1...
      3. Got response: Success
      4. Calling GetDataAsync on MyActor:1...
      5. Got response: Success