Skip to content

Instantly share code, notes, and snippets.

@kadukf
Created December 9, 2013 09:29
Show Gist options
  • Save kadukf/7869629 to your computer and use it in GitHub Desktop.
Save kadukf/7869629 to your computer and use it in GitHub Desktop.
selfhosting WCF service in WorkerRole
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using WcfWorkerRole.Impl;
namespace WcfWorkerRole
{
public class WorkerRole : RoleEntryPoint
{
private WebServiceHost _serviceHost;
public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.TraceInformation("WcfWorkerRole entry point called", "Information");
base.Run();
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
StartWCFService();
return base.OnStart();
}
private void StartWCFService()
{
Trace.TraceInformation("Starting WCF service host...");
IPEndPoint endpoint = GetInstanceEndpoint("httpIn");
var address = new Uri(string.Format("http://{0}/", endpoint));
_serviceHost = new WebServiceHost(typeof(ProductsService), address);
try
{
_serviceHost.Open();
Trace.TraceInformation("WCF service host started successfully.");
}
catch (TimeoutException timeoutException)
{
Trace.TraceError("The service operation timed out. {0}", timeoutException.Message);
}
catch (CommunicationException communicationException)
{
Trace.TraceError("Could not start WCF service host. {0}", communicationException.Message);
}
}
private static IPEndPoint GetInstanceEndpoint(string endpointName)
{
if (RoleEnvironment.IsAvailable)
{
return RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endpointName].IPEndpoint;
}
return new IPEndPoint(IPAddress.Loopback, int.Parse(ConfigurationManager.AppSettings[endpointName]));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment