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

news/2024/5/19 23:43:22 标签: .netcore

一、客户端工厂概述

  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文件 可以看我之前的文章这里就不放上来了
    /// <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();
        }

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

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

四、执行效果展示

客户端:

 服务端:

 五、源码地址

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


http://www.niftyadmin.cn/n/4947287.html

相关文章

【Docker】docker数据卷(数据挂载)持久化

docker数据卷&#xff08;数据挂载&#xff09;持久化 一、docker对于数据的管理二、docker挂载主机目录---指定路径挂载三、docker使用数据卷Volume挂载四、数据共享--数据卷容器五、备份和恢复 docker的镜像是由多个只读的文件系统叠加在一起形成的。当我们在我启动一个容器的…

边缘计算节点BEC典型实践:如何快速上手PC-Farm服务器?

百度智能云边缘计算节点BEC&#xff08;Baidu Edge Computing&#xff09;基于运营商边缘节点和网络构建&#xff0c;一站式提供靠近终端用户的弹性计算资源。边缘计算节点在海外覆盖五大洲&#xff0c;在国内覆盖全国七大区、三大运营商。BEC通过就近计算和处理&#xff0c;大…

一次Linux中的木马病毒解决经历(6379端口---newinit.sh)

病毒入侵解决方案 情景 最近几天一直CPU100%,也没有注意看到了以为正常的服务调用,直到腾讯给发了邮件警告说我的服务器正在入侵其他服务器的6379端口,我就是正常的使用不可能去入侵别人的系统的,这是违法的. 排查 既然入侵6379端口,就怀疑是通过我的Redis服务进入的我的系统…

自然语言处理从入门到应用——LangChain:索引(Indexes)-[基础知识]

分类目录&#xff1a;《自然语言处理从入门到应用》总目录 索引&#xff08;Indexes&#xff09;是指为了使LLM与文档更好地进行交互而对其进行结构化的方式。在链中&#xff0c;索引最常用于“检索”步骤中&#xff0c;该步骤指的是根据用户的查询返回最相关的文档&#xff1a…

非常详细的 Ceph 介绍、原理、架构

1. Ceph架构简介及使用场景介绍 1.1 Ceph简介 Ceph是一个统一的分布式存储系统&#xff0c;设计初衷是提供较好的性能、可靠性和可扩展性。 Ceph项目最早起源于Sage就读博士期间的工作&#xff08;最早的成果于2004年发表&#xff09;&#xff0c;并随后贡献给开源社区。在经过…

【NEW】视频云存储EasyCVR平台H.265转码配置增加分辨率设置

关于视频分析EasyCVR视频汇聚平台的转码功能&#xff0c;我们在此前的文章中也介绍过不少&#xff0c;感兴趣的用户可以翻阅往期的文章进行了解。 安防视频集中存储EasyCVR视频监控综合管理平台可以根据不同的场景需求&#xff0c;让平台在内网、专网、VPN、广域网、互联网等各…

图论相关问题

1. 拓扑排序bitset 第一次使用bitset&#xff0c;复杂度&#xff1a;N/32&#xff0c;比N小 所以总的时间复杂度为O(N*(NM)/32) #include <iostream> #include <bitset> #include <queue> using namespace std; const int N 3e420; bitset<N> f[N];…

SOLIDWORKS镜向是什么?

在现代工程设计中&#xff0c;使用CAD软件是必不可少的。SOLIDWORKS作为一款功能强大的三维建模软件&#xff0c;提供了众多的工具和功能&#xff0c;帮助工程师以更高的效率进行设计。其中&#xff0c;SOLIDWORKS 镜向功能被广泛应用于设计过程中&#xff0c;为用户带来了许多…