依赖注入GRPC客户端
/// <summary> /// 注入grpc接口 /// </summary> /// <typeparam name="TService">需要创建连接的接口</typeparam> /// <param name="services"></param> public static void AddGrpcScoped<TService>(this IServiceCollection services) where TService : class {
var grpcChannel = GrpcChannel.ForAddress('http://url', new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { EnableMultipleHttp2Connections = true, } });
var grpcService = grpcChannel.CreateGrpcService<IProductService>();
services.AddScoped<TService>(sp => { return grpcService; }); }
使用:
readonly IProductAppService _productAppService; public WeChatController(IProductAppService productAppService) { _productAppService = productAppService; }
/// <summary>
/// 获取一个登录用的qrcode
/// </summary>
/// <returns></returns>
[Route("test"), AllowAnonymous]
public async Task<IActionResult> test()
{
try
{
var model = await _productAppService.GetListAsync();
return new JsonResult(model);
} catch (RpcException e)
{
}
}