WCF自定义绑定用于压缩

3

根据微软提供的压缩示例,我已经将编码器、编码器工厂和绑定元素添加到我的解决方案中。与他们的示例不同的是,我们不通过配置文件注册端点(要求),而是使用自定义的服务主机工厂。

服务主机:

protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
     ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

     if (host.Description.Endpoints.Count == 0)
     {
          host.AddDefaultEndpoints();
     }

     host.Description.Behaviors.Add(new MessagingErrorHandler());      

     return host;
}

所以我尝试为我的端点添加自定义绑定,但要使用AddServiceEndpoint注册该端点到绑定似乎需要一个未知的接口。我知道我可以获取serviceType实现的所有接口并执行getInterfaces()[0],但这对我来说似乎是不安全的方法。
那么有没有一种方法可以在不知道接口的情况下注册我的端点到自定义绑定,或者也许我应该采取更好的方法。
我尝试添加自定义绑定的方法:
CustomBinding compression = new CustomBinding();
compression.Elements.Add(new GZipMessageEncodingBindingElement());
foreach (var uri in baseAddresses)
{
     host.AddServiceEndpoint(serviceType, compression, uri);//service type is not the interface and is causing the issue
}

你能说明一下为什么接口是未知的吗?也许我误解了,但是看起来你要么定义了服务端点(因此应该有接口),要么没有 - 所以不需要进行绑定。 - Basic
serviceType 可能有多个接口,因此我不知道将哪些接口分配给端点。 - DisplayName
你如何使用标准绑定(例如NetTcpBinding)注册终结点? - Bernard
1个回答

3

您的自定义绑定需要一个传输绑定元素;目前只有一个消息编码绑定元素。您需要将 HttpTransportBindingElement 添加到您的自定义绑定中:

CustomBinding compression = new CustomBinding(
    new GZipMessageEncodingBindingElement()
    new HttpTransportBindingElement());

就从服务类型中找到接口而言,没有内置逻辑。 WebServiceHostFactory 中使用的逻辑类似于下面显示的逻辑(此代码向下 1 继承 / 实现级别,但理论上您也可以更深入)。

    private Type GetContractType(Type serviceType) 
    { 
        if (HasServiceContract(serviceType)) 
        { 
            return serviceType; 
        } 

        Type[] possibleContractTypes = serviceType.GetInterfaces() 
            .Where(i => HasServiceContract(i)) 
            .ToArray(); 

        switch (possibleContractTypes.Length) 
        { 
            case 0: 
                throw new InvalidOperationException("Service type " + serviceType.FullName + " does not implement any interface decorated with the ServiceContractAttribute."); 
            case 1: 
                return possibleContractTypes[0]; 
            default: 
                throw new InvalidOperationException("Service type " + serviceType.FullName + " implements multiple interfaces decorated with the ServiceContractAttribute, not supported by this factory."); 
        } 
    } 

    private static bool HasServiceContract(Type type) 
    { 
        return Attribute.IsDefined(type, typeof(ServiceContractAttribute), false); 
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接