Manage Service Bus Connectivity Mode
How do we manage Service Bus Connectivity Mode while hosting WCF Service with Service Bus Endpoints on IIS?
Hosting WCF Services with Service Bus Endpoints on IIS
https://msdn.microsoft.com/en-us/library/windowsazure/hh966775.aspx
Relevant Facts and Documentaion:
- Service Bus Listener uses AutoDetect mode by default, however you can set it to other modes explicitly. (Source: https://msdn.microsoft.com/en-us/library/windowsazure/microsoft.servicebus.connectivitymode.aspx).
- Auto-detect mode probes the connectivity options in the order - TCP, HTTP and HTTPS. HTTPS is only supported for Service Bus Relay till date (Microsoft.ServiceBus.dll 1.8 and newer), not for Brokered Messaging. The default mode for brokered messaging is TCP and if HTTP is required, you have to explicitly specify it.
- The Service Bus Listener gets created when WCF Service Host is opened. All this code is instrumented for your convenience by the WCF assemblies when hosted in IIS. However, you can intercept this and customize by overriding the CreateServiceHost method in the WCF ServiceHostFactory class.
Solution:
- For the scenario, described above - you can use configuration appsettings to manage connectivity mode and alter it by overriding CreateServiceHost.
<configuration>
……………
<appSettings>
<add key="connMode" value="http"/>
</appSettings>
………………
</configuration>
public class CustomServiceFactory : ServiceHostFactory {
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new SelfDescribingServiceHost(serviceType, baseAddresses);
}
}
class SelfDescribingServiceHost : ServiceHost
{
public SelfDescribingServiceHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses) { }
//Overriding ApplyConfiguration() allows us to alter the ServiceDescription prior to opening
//the service host.
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
string cmode = ConfigurationManager.AppSettings.Get("connMode");
if (cmode == "http")
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
else
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Tcp;
}
}
- Also, make sure you WCF service page is made aware of it by changing the page as follows.
From:
<%@ ServiceHost Language="C#" Debug="true" Service="<namespace>.Service1" CodeBehind="Service1.svc.cs" %>
To:
<%@ ServiceHost Language="C#" Debug="true" Service="<namespace>.Service1" Factory="<namespace>.CustomServiceFactory" %>