1. 添加自定義實現類 CustomProvider數據庫
public class CustomProvider : IGrainStorage { public Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { throw new NotImplementedException(); } public Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if(grainType== "Grain.UserGrain") { var id = grainReference.GetPrimaryKeyLong(); //模擬從數據庫讀出User var user = new UserState() { MobilePhone = "124214214", Name = "李四" }; grainState.State = user; } return Task.CompletedTask; } public Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (grainType== "Grain.UserGrain") { var id = grainReference.GetPrimaryKeyLong(); //模擬保存數據庫 } return Task.CompletedTask; } }
2. 在silo中注入代替默認實現ide
.ConfigureServices(services => { var providerName = "CustomProvider"; services.TryAddSingleton(sp => sp.GetServiceByName<IGrainStorage>(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME)); services.AddSingletonNamedService<IGrainStorage, CustomProvider>(providerName); })
3. 在grain類上啓用spa
[StorageProvider(ProviderName = "CustomProvider")]
示例代碼下載地址:SimpleStoragecode