I didn’t found the documentation really clear on the steps involved when using Grain Persistence in combination with PostgreSQL.
So here is my attempt to describe the process:
- Add a reference to the following NuGet packages:
- Update the cluster configuration to add the storage:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.AddAdoNetGrainStorage("OrleansStorage", options => | |
{ | |
options.Invariant = "Npgsql"; | |
options.ConnectionString = "host=192.168.0.1;database=orleans;password=orleans;username=orleanssample"; | |
options.UseJsonFormat = true; | |
}) |
- Invariant should be set to ‘npgsql’
- ConnectionString should be set to the connection to the PostgreSQL instance you want to use
- UseJsonFormat should be set to true as PostgreSQL has good Json support.
- Let your grain inherit from Grain<> and specify a state object:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GrainState | |
{ | |
public GrainState() | |
{ | |
this.Greetings = new List<string>(); | |
} | |
public List<string> Greetings { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HelloGrain : Grain<GrainState>, IHello | |
{ | |
public async Task<string> SayHello(string greeting) | |
{ | |
this.State.Greetings.Add(greeting); | |
await this.WriteStateAsync(); | |
return greeting; | |
} | |
} |
- Add a StorageProvider attribute on top of your Grain and set the name to the storage name you used inside the cluster config
- In our example we had set this to ‘OrleansStorage’:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[StorageProvider(ProviderName = "OrleansStorage")] | |
public class HelloGrain : Grain<GrainState>, IHello | |
{ | |
} |
- Execute the PostgreSQL-Main.sql and PostgreSQL-Persistence.sql scripts inside the OrleansAdoNetContent/PostgreSQL folder to create the necessary database objects
- Now you are good to go!