.netcore grpc客户端工厂及依赖注入使用

一、客户端工厂概述

  1. gRPC 与 HttpClientFactory 的集成提供了一种创建 gRPC 客户端的集中方式。
  2. 可以通过依赖包Grpc.Net.ClientFactory中的AddGrpcClient进行gRPC客户端依赖注入
  3. AddGrpcClient函数提供了许多配置项用于处理一些其他事项;例如AOP、重试策略等

二、案例介绍

  1. 创建一个WPF客户端
  2. 在App.xaml.cs代码类里重写OnStartup方法,进行依赖注入;需要注意的是在方法内设立窗口调用需要把展示端属性  xmlns: StartupUri="FieldWindow.xaml 给去掉
  3. 引用ServiceCollection做为容器集
  4. 注入gRPC工厂,注入windows窗体,以及其他需要用到的服务类等

三、客户端代码展示

  1. proto文件 可以看我之前的文章这里就不放上来了
    /// 
    /// Interaction logic for App.xaml
    /// 
    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.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
    {
        /// 
        /// rpc 工厂注入
        /// 
        /// 
        /// 
        public static IServiceCollection AddWPFGrpc(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            services.AddGrpcClient(options => options.Address = new Uri("https://localhost:7188"));

            return services;
        }
    }
    /// 
    /// FieldWindow.xaml 的交互逻辑
    /// 
    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();
        }

        // null
        private async void BtnNullconfig_Click(object sender, RoutedEventArgs e)
        {

            // null
            NullConfig 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();
        }

        // list
        private async void BtnListconfig_Click(object sender, RoutedEventArgs e)
        {
            // ListConfig
            ListConfig listConfig = new ListConfig();
            var attributes = new Dictionary
            {
                [1] = "one",
                [2] = "two",
                [3] = "three",
                [4] = "four",
                [5] = "five"
            };

            listConfig.Id = 123456456;
            listConfig.Attributes.Add(attributes);

            var dicDetail = new Dictionary
            {
                [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
            {
               new ListDetailConfig { Height=9,Name="nine"},
               new ListDetailConfig{ Height=10,Name="ten"}
            };

            listConfig.Details.Add(detailConfigs);


            await _fieldRpcClient.ListConfigServiceAsync(listConfig);

            MessageBox();
        }

        // any
        private async void BtnAnyconfig_Click(object sender, RoutedEventArgs e)
        {
            // Any
            AnyConfig anyConfig = new AnyConfig();
            anyConfig.Id = 42564134;

            anyConfig.AnyObject = Any.Pack(new B { Id = 15 });

            await _fieldRpcClient.AnyConfigServiceAsync(anyConfig);
            
            MessageBox();
        }

        // Oneof
        private async void BtnOneofconfig_Click(object sender, RoutedEventArgs e)
        {

            // Oneof
            OneofConfig 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);
        }
    }

四、执行效果展示

客户端:

.netcore grpc客户端工厂及依赖注入使用_第1张图片

 服务端:

.netcore grpc客户端工厂及依赖注入使用_第2张图片

 五、源码地址

链接:https://pan.baidu.com/s/1FQY7QOgF8Y90igKV56Yupg 
提取码:mbyg

你可能感兴趣的:(.netcore)