Microsoft Orleans persistence providers backed by ADO.NET
$ dotnet add package Microsoft.Orleans.Persistence.AdoNetMicrosoft Orleans Persistence for ADO.NET provides grain persistence for Microsoft Orleans using relational databases through ADO.NET. This provider allows your grains to persist their state in various relational databases including SQL Server, MySQL, PostgreSQL, and Oracle.
To use this package, install it via NuGet:
dotnet add package Microsoft.Orleans.Persistence.AdoNet
You will also need to install the appropriate database driver package for your database system:
Microsoft.Data.SqlClient or System.Data.SqlClientMySql.Data or MySqlConnectorNpgsqlOracle.ManagedDataAccess.CoreMicrosoft.Data.Sqliteusing Microsoft.Extensions.Hosting;
using Orleans.Configuration;
using Orleans.Hosting;
var builder = Host.CreateApplicationBuilder(args)
.UseOrleans(siloBuilder =>
{
siloBuilder
.UseLocalhostClustering()
// Configure ADO.NET as grain storage
.AddAdoNetGrainStorage(
name: "AdoNetStore",
configureOptions: options =>
{
options.Invariant = "System.Data.SqlClient"; // Or other providers like "MySql.Data.MySqlClient", "Npgsql", etc.
options.ConnectionString = "Server=localhost;Database=OrleansStorage;User Id=myUsername;******;";
// Optional: Configure custom queries
options.UseJsonFormat = true; // Store as JSON instead of binary
});
});
// Run the host
await builder.RunAsync();
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
// Define grain state class
public class MyGrainState
{
public string Data { get; set; }
public int Version { get; set; }
}
// Grain implementation that uses the ADO.NET storage
public class MyGrain : Grain, IMyGrain, IGrainWithStringKey
{
private readonly IPersistentState<MyGrainState> _state;
public MyGrain([PersistentState("state", "AdoNetStore")] IPersistentState<MyGrainState> state)
{
_state = state;
}
public async Task SetData(string data)
{
_state.State.Data = data;
_state.State.Version++;
await _state.WriteStateAsync();
}
public Task<string> GetData()
{
return Task.FromResult(_state.State.Data);
}
}
Before using the ADO.NET provider, you need to set up the necessary database tables. Scripts for different database systems are available in the Orleans source repository:
For more comprehensive documentation, please refer to: