一、客户端工厂概述
- 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
下一篇https://blog.csdn.net/qq_31975127/article/details/132346657