一、客戶端工廠概述
- gRPC 與?
HttpClientFactory
?的集成提供了一種創建 gRPC 客戶端的集中方式。 - 可以通過依賴包Grpc.Net.ClientFactory中的AddGrpcClient進行gRPC客戶端依賴注入
- AddGrpcClient函數提供了許多配置項用于處理一些其他事項;例如AOP、重試策略等
二、案例介紹
- 創建一個WPF客戶端
- 在App.xaml.cs代碼類里重寫OnStartup方法,進行依賴注入;需要注意的是在方法內設立窗口調用需要把展示端屬性??xmlns: StartupUri="FieldWindow.xaml 給去掉
- 引用ServiceCollection做為容器集
- 注入gRPC工廠,注入windows窗體,以及其他需要用到的服務類等
三、客戶端代碼展示
- proto文件 可以看我之前的文章這里就不放上來了
/// <summary>/// Interaction logic for App.xaml/// </summary>public partial class App : Application{protected override void OnStartup(StartupEventArgs e){IServiceCollection services = new ServiceCollection();// 注入services.AddWPFGrpc();AddWPFWindows(services);// 構建服務提供器var serviceProvider = services.BuildServiceProvider();var fieldWindow = serviceProvider.GetRequiredService<FieldWindow>();fieldWindow.Show();}private IServiceCollection AddWPFWindows(IServiceCollection services){if (services == null){throw new ArgumentNullException(nameof(services));}var windowType = typeof(Window);var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.BaseType == windowType).ToList();foreach (var type in types){services.AddScoped(type);}return services;}}
public static class GrpcClient{/// <summary>/// rpc 工廠注入/// </summary>/// <param name="services"></param>/// <returns></returns>public static IServiceCollection AddWPFGrpc(this IServiceCollection services){if (services == null){throw new ArgumentNullException(nameof(services));}services.AddGrpcClient<FieldRpc.FieldRpcClient>(options => options.Address = new Uri("https://localhost:7188"));return services;}}
/// <summary>/// FieldWindow.xaml 的交互邏輯/// </summary>public partial class FieldWindow : Window{private readonly FieldRpc.FieldRpcClient _fieldRpcClient;public FieldWindow( FieldRpc.FieldRpcClient fieldRpcClient){InitializeComponent();_fieldRpcClient = fieldRpcClient;}// 基礎private async void BtnBaseconfig_Click(object sender, RoutedEventArgs e){// 基礎BaseConfig config = new BaseConfig();config.Name = "張三";config.Position = 2.33D;config.Distance = 5.48F;config.Age = 10;config.TimeSpanId = 6538590027736100;config.SAge = 1921;config.STimeSpanId = 6538590027736130;config.Flag = true;await _fieldRpcClient.BaseConfigServiceAsync(config);MessageBox();}// 日期private async void BtnDateconfig_Click(object sender, RoutedEventArgs e){// 日期DateConfig dateConfig = new DateConfig();dateConfig.Id = 179;dateConfig.DateDuration = Google.Protobuf.WellKnownTypes.Duration.FromTimeSpan(TimeSpan.FromSeconds(5));// 注意這里的時間是utc時間dateConfig.DateTimestamp = Timestamp.FromDateTime(DateTime.UtcNow);await _fieldRpcClient.DateConfigServiceAsync(dateConfig);MessageBox();}// 字節private async void BtnByteconfig_Click(object sender, RoutedEventArgs e){// 字節ByteConfig byteConfig = new ByteConfig();byteConfig.Id = 9854564654654;byteConfig.PositionBytes = ByteString.CopyFrom(Encoding.UTF8.GetBytes("莊這人的南的很"));await _fieldRpcClient.ByteConfigServiceAsync(byteConfig);MessageBox();}// nullprivate async void BtnNullconfig_Click(object sender, RoutedEventArgs e){// nullNullConfig nullConfig = new NullConfig();nullConfig.Id = 1854564654654;nullConfig.NullBool = true;nullConfig.NullFloat = null;nullConfig.NullUInt = null;nullConfig.NullInt = 15;nullConfig.NullLong = 112345451234787;await _fieldRpcClient.NullConfigServiceAsync(nullConfig);MessageBox();}// listprivate async void BtnListconfig_Click(object sender, RoutedEventArgs e){// ListConfigListConfig listConfig = new ListConfig();var attributes = new Dictionary<int, string>{[1] = "one",[2] = "two",[3] = "three",[4] = "four",[5] = "five"};listConfig.Id = 123456456;listConfig.Attributes.Add(attributes);var dicDetail = new Dictionary<int, ListDetailConfig>{[1] = new ListDetailConfig { Height = 1, Name = "one" },[2] = new ListDetailConfig { Height = 2, Name = "two" },[3] = new ListDetailConfig { Height = 3, Name = "three" },[4] = new ListDetailConfig { Height = 4, Name = "four" },[5] = new ListDetailConfig { Height = 5, Name = "five" }};listConfig.DicDetail.Add(dicDetail);listConfig.Details.Add(new ListDetailConfig { Height = 8, Name = "Eight" });var detailConfigs = new List<ListDetailConfig>{new ListDetailConfig { Height=9,Name="nine"},new ListDetailConfig{ Height=10,Name="ten"}};listConfig.Details.Add(detailConfigs);await _fieldRpcClient.ListConfigServiceAsync(listConfig);MessageBox();}// anyprivate async void BtnAnyconfig_Click(object sender, RoutedEventArgs e){// AnyAnyConfig anyConfig = new AnyConfig();anyConfig.Id = 42564134;anyConfig.AnyObject = Any.Pack(new B { Id = 15 });await _fieldRpcClient.AnyConfigServiceAsync(anyConfig);MessageBox();}// Oneofprivate async void BtnOneofconfig_Click(object sender, RoutedEventArgs e){// OneofOneofConfig oneofConfig = new OneofConfig();oneofConfig.OA = new A { Id = 1 };//oneofConfig.OC = new C { Id = 2 };await _fieldRpcClient.OneofConfigServiceAsync(oneofConfig);MessageBox();}private void MessageBox(){string messageBoxText = "執行完成";string caption = "HELLO";MessageBoxButton button = MessageBoxButton.OK;MessageBoxImage icon = MessageBoxImage.Information;MessageBoxResult result = System.Windows.MessageBox.Show(messageBoxText, caption, button, icon);}}
四、執行效果展示
客戶端:
?服務端:
?五、源碼地址
鏈接:https://pan.baidu.com/s/1FQY7QOgF8Y90igKV56Yupg?
提取碼:mbyg