【问题标题】:WCF custom binding for compression用于压缩的 WCF 自定义绑定
【发布时间】:2012-05-25 10:27:48
【问题描述】:

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

服务主机:

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
}

【问题讨论】:

  • 你能解释一下为什么接口是未知的吗?也许我误解了,但似乎你要么定义服务端点(所以应该有接口),或者你没有 - 所以不需要绑定。
  • serviceType 可能有多个接口,所以我不知道将哪些接口分配给端点
  • 您如何使用您的端点注册标准绑定之一,例如NetTcpBinding

标签: wcf .net-4.0 compression http-compression wcf-endpoint


【解决方案1】:

您的自定义绑定需要一个传输绑定元素;目前您只有一个消息编码绑定元素。您可能还需要在自定义绑定中添加 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); 
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多