Example of running and using virtual actors in the .NET SDK

    The Dapr actor package allows you to interact with Dapr virtual actors from a .NET application.

    Overview

    This document describes how to create an Actor () and 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 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.

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

    Step 1: Create actor interfaces

    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
    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
    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. }
    1. # Create ASP.Net Web service to host Dapr actor
    2. dotnet new web -o MyActorService
    3. # Add Dapr.Actors.AspNetCore nuget package. Please use the latest package version from nuget.org
    4. dotnet add package Dapr.Actors.AspNetCore -v 1.0.0
    5. # Add Actor Interface reference
    6. dotnet add reference ../MyActor.Interfaces/MyActor.Interfaces.csproj
    7. 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 UseEndpoints(...) inside .

    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. app.UseHttpsRedirection();
    24. app.UseRouting();
    25. app.UseEndpoints(endpoints =>
    26. {
    27. // Register actors handlers that interface with the Dapr runtime.
    28. endpoints.MapActorsHandlers();
    29. });
    30. }
    31. }
    32. }

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

    You can use ActorProxy.Create<IMyActor>(..) to create a strongly-typed client and invoke methods on the actor.

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

    Now you have successfully created an actor service and client. See the related links section to learn more.