Banshee
Banshee

Reputation: 15837

How to add custom Behavior to WCF ServiceHost programmatically?

I have the following in my config :

<behaviors>
<endpointBehaviors>
        <behavior name="protoEndpointBehavior">
          <protobuf />
        </behavior>
      </endpointBehaviors>
    </behaviors>

How do I add the protobuf behavior programmatically instead of having it in the config file?

I have this code so far :

ServiceHost serviceHost = null;
                Console.WriteLine("Creating service " + serviceType.FullName);
                serviceHost = new MyServiceHost(serviceType, uriList.Select(c => new Uri(c)).ToArray());

                serviceHost = new MyServiceHost(serviceType, uriList.Select(c => new Uri(c)).ToArray());

                if (secureConnectionSettings != null && secureConnectionSettings.Enabled)
                {
                    Console.WriteLine("Setting certificates");
                    X509Store store = new X509Store(secureConnectionSettings.CertificateStore, secureConnectionSettings.CertificateLocation);
                    store.Open(OpenFlags.ReadOnly);
                    X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, secureConnectionSettings.Thumbprint, true);
                    store.Close();

                    if (certs.Count > 0)
                        serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, secureConnectionSettings.Thumbprint);
                    else
                        throw new Exception("Could not finde certificate with thumbprint " + secureConnectionSettings.Thumbprint);
                }

                var binding = CreateNetHttpBinding();

                var endpoint = new System.ServiceModel.Description.ServiceEndpoint(new System.ServiceModel.Description.ContractDescription("My.ServiceContracts.IMyClientService"), binding, new EndpointAddress("BinaryHttpProto"));
                endpoint.EndpointBehaviors.Add( new ProtoBuf.ServiceModel.ProtoBehaviorExtension());
                serviceHost.AddServiceEndpoint(endpoint);

The following line do not work :

endpoint.EndpointBehaviors.Add( new ProtoBuf.ServiceModel.ProtoBehaviorExtension());

Upvotes: 1

Views: 2045

Answers (1)

tomasr
tomasr

Reputation: 13859

I don't know much about that library, but you're trying to add the configuration extension element, rather than the actual behavior.

Does it work if you do this instead?

endpoint.EndpointBehaviors.Add( new ProtoBuf.ServiceModel.ProtoEndpointBehavior());

Upvotes: 1

Related Questions