首页 > 解决方案 > 当代码以部分信任运行时,无法新建 gRPC.Core.Channel 实例

问题描述

Grpc.Core.Channel 用于调用服务。当代码在部分信任环境中运行时,会弹出以下错误。

“类型违反的继承安全规则:'Grpc.Core.internal.SafeHandleZeroIsInvalid' 派生类型必须与基类型的安全可访问性匹配或难以访问”

如何在部分信任的环境中使用 Channel 调用 Grpc 服务?如果不能,还有其他方法可以调用 Grpc 服务吗?

查看 gRPC 代码,一个 .net 类 SafeHandle 由 SafeHandleZeroIsInvalid 继承。如官方文档所述,对于部分受信任的代码,是不允许的。SafeHandle 的 InheritanceDemand 是:“对于继承者的完全信任。这个成员不能被部分信任的代码继承。” https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.safehandle?view=netframework-4.8

我尝试创建自己的类,该类继承自 SafeHandle。而且,我尝试新建这个类的一个实例。当代码在部分信任中运行时,会弹出相同的错误。我认为 SafeHandle 是导致此问题的根本原因。

//the code is super simple, I just try to create a channel on a constructor. 
public class WriterClient
{
    private Channel _channel;
    private LoggingCenter _logger;
    public WriterClient(int port, ILogging logger)
    {
        _logger = logger == null? new LoggingCenter(new NullLogger()): new LoggingCenter(logger);
        //when run in Partial Trust, the code below will throw an exception.
        _channel = new Channel("127.0.0.1", port, ChannelCredentials.Insecure);            
    }

我想要的是在部分信任中正确调用 Grpc 服务。有什么解决方法吗?

标签: c#clientgrpcpartial-trust

解决方案


推荐阅读