The Azure Functions ecosystem introduced a new member; durable entities also know as entity functions.
Durable entities behave like tiny services that communicate via messages. Each entity has a unique identity and an internal state (if it exists). In that way they are quite similar to actors in the actor model. (However there are some important differences in the way they are implemented compared to Orleans or Akka.net).
There are 2 ways to create entities:
- The class-based syntax represents entities and operations as classes and methods. This syntax produces easily readable code and allows operations to be invoked in a type-checked manner through interfaces.
-
The function-based syntax is a lower-level interface that represents entities as functions. It provides precise control over how the entity operations are dispatched, and how the entity state is managed.
Let’s have a look at the class-based syntax as this is more familiar for people coming from another actor framework.
This functionality is available through the Microsoft.Azure.WebJobs.Extensions.DurableTask nuget package.
We first need to define an entity class. This class can have methods and properties just like a ‘normal’ class.
Notice 2 things:
- We keep our state private and only make it accessible through a method call.
- You can clear the entity state through calling Entity.Current.DeleteState().
Remark: It is important to follow the CQS principle when using durable entities. A method should either return data (query) or update state(command) but never do both.
There is one extra step we need to take. A Run function should be added. This function contains the boilerplate required for using the class-based syntax. It must be a static Azure Function. It executes once for each operation message that is processed by the entity. When DispatchAsync<T>
is called and the entity isn't already in memory, it constructs an object of type T
and populates its fields from the last persisted JSON found in storage (if any). Then it invokes the method with the matching name.
To call our entity we can use the IDurableEntityClient. An entity can either be signaled or called:
- Calling an entity uses two-way (round-trip) communication. You send an operation message to the entity, and then wait for the response message before you continue. The response message can provide a result value or an error result, such as a JavaScript error or a .NET exception. This result or error is then observed by the caller.
- Signaling an entity uses one-way (fire and forget) communication. You send an operation message but don't wait for a response. While the message is guaranteed to be delivered eventually, the sender doesn't know when and can't observe any result value or errors.
An example: