gRPC入门学习之旅(十)

3.12、依赖注入方式调用gRPC

1. 在Visual Studio 2022的解决方案资源管理器中,使用鼠标右键单击“Command”文件夹,在弹出菜单中选择“添加--> 类”,在弹出的“添加新项”对话框中,选择添加 “UserIoc.cs”类,这是一个我们要实现的依赖注入的类,然后选择“添加”。

2. 在Visual Studio 2022的解决方案资源管理器中,使用鼠标双击打开“UserIoc.cs”文件,并添加如下具体代码。

using Demo.GrpcService.Protos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Demo.Grpc.Client
{
    internal class UserIoc
    {

        /// <summary>
        /// 定义gRPC客户端服务对象
        /// </summary>

        private readonly UserInfo.UserInfoClient _userClient;

        public UserIoc(UserInfo.UserInfoClient userClient)

        {

            _userClient = userClient;
        }

        public string GetUserInfo()
        {
            var userInfo = _userClient.GetUserInfo(new UserInfoRequest()
            {

                UserName="IocTest",
                Password = "GRPC 依赖注入调用方式- IOC"

            });

            return JsonSerializer.Serialize(userInfo);

        }
}

}

 

 

3. 在MainWindows.xmal文件中添加一个Buttion控件,并使用鼠标双击这个按钮,在MainWindows.xmal.cs文件中添加一个btnIocTestUserInfo_Click事件,具体代码如下:

<Button x:Name="btnIocTestUserInfo" Grid.Column="2" Grid.Row="0" Content="Ioc用户信息" Click="btnIocTestUserInfo_Click"></Button>

4.在MainWindows.xmal.cs文件的btnIocTestUserInfo_Click事件中,添加依赖注入的代码。具体代码如下:

        private void btnIocTestUserInfo_Click(object sender, RoutedEventArgs e)
        {
            #region 使用IOC注入的方式调用gRPC
            IServiceCollection services = new ServiceCollection();

 
            //注册UserIoc服务
            services.AddTransient<UserIoc>();

            #region gRPC Client注册

            //调用http时启用该设置
            //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            //添加gRPC客户端服务
            services.AddGrpcClient<UserInfo.UserInfoClient>(options =>
            {
                //设置gRPC的https服务调用地址
                options.Address = new Uri("https://localhost:7149");

            }).ConfigureChannel(grpcOptions =>
            {
            });
            #endregion
            //构建容器
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            //解析UserIoc服务

            var grpcRequestTest = serviceProvider.GetService<UserIoc>();
            //调用UserIoc服务中的GetUserInfo方法

           txtMsg.Text= grpcRequestTest.GetUserInfo();
            #endregion
        }

5.新开一个Visual Studio 2022,打开Demo.GrpcService解决方案,并在Visual Studio 2022的解决方案资源管理器中,将Demo.GrpcService项目设为启动项目。按F5,启动。如图。

 

6.在第一个Visual Studio 2022中,我们按F5,将Grpc.Demo.Client运行起来。然后点击“Ioc用户信息”按钮,实现Ioc调用grpc的方法 。如图

 

posted @ 2024-06-08 10:50  DotNet菜园  阅读(265)  评论(0编辑  收藏  举报