WCF自定义绑定用于压缩

时间:2012-05-17 19:55:38

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

遵循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
}

1 个答案:

答案 0 :(得分:2)

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