Summary: This article explains how to develop durable entities in .NET using Azure Functions, focusing on defining entity classes and accessing them. It includes examples of operations like adding, resetting, and retrieving values from a Counter entity. Additionally, it highlights best practices for using interfaces and entity context for effective entity management.
two ways of defining an entity as a class in the C# isolated worker model. They produce entities with different state serialization structures. (View Highlight)
following approach, the entire object is serialized when defining an entity (View Highlight)
public class Counter { public int Value { get; set; } public void Add(int amount) { this.Value += amount; } public Task Reset() { this.Value = 0; return Task.CompletedTask; } public Task Get() { return Task.FromResult(this.Value); } // Delete is implicitly defined when defining an entity this way [Function(nameof(Counter))] public static Task Run([EntityTrigger] TaskEntityDispatcher dispatcher) => dispatcher.DispatchAsync(); } (View Highlight)
A TaskEntity<TState>-based implementation, which makes it easy to use dependency injection. In this case, state is deserialized to the State property, and no other property is serialized/deserialized. (View Highlight)
public class Counter : TaskEntity { readonly ILogger logger; public Counter(ILogger logger) { this.logger = logger; } public int Add(int amount) { this.State += amount; } public Reset() { this.State = 0; return Task.CompletedTask; } public Task Get() { return Task.FromResult(this.State); } // Delete is implicitly defined when defining an entity this way [Function(nameof(Counter))] public static Task Run([EntityTrigger] TaskEntityDispatcher dispatcher) => dispatcher.DispatchAsync(); } (View Highlight)