WCF custom binding for compression

Following the sample compression from Microsoft. I added an encoder, a factory encoder, and a binding element to my solution. The difference from their selection is that we do not register our endpoints through the configuration file (requirement), but instead use our own Factory service host.

Service Host:

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;
}

So, I tried to add a custom binding to my endpoint, but to register this endpoint with a binding seems to be what I need to use AddServiceEndpoint, but this will require an interface that is unknown. I know that I can get all the interfaces that serviceType implements and do it getInterfaces()[0], but it seems to me unsafe. So, there is a way to register my user-defined endpoint and not know the interface, or maybe the best approach I should take.

My attempt to add a custom binding:

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
}
+3
source share
1 answer

; . , , HttpTransportBindingElement :

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

, . , WebServiceHostFactory, , ( / , .

    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); 
    }
+2

Source: https://habr.com/ru/post/1626650/


All Articles