一丶簡單介紹下目錄結構和項目依賴,如圖 二丶主要核心自定義代碼 1. 添加自定義實現類 CustomProvider 2. 在silo中註入代替預設實現 3. 在grain類上啟用 三丶運行結果如下 示例代碼下載地址:SimpleStorage ...
一丶簡單介紹下目錄結構和項目依賴,如圖
二丶主要核心自定義代碼
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中註入代替預設實現
.ConfigureServices(services => { var providerName = "CustomProvider"; services.TryAddSingleton(sp => sp.GetServiceByName<IGrainStorage>(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME)); services.AddSingletonNamedService<IGrainStorage, CustomProvider>(providerName); })
3. 在grain類上啟用
[StorageProvider(ProviderName = "CustomProvider")]
三丶運行結果如下
示例代碼下載地址:SimpleStorage