Introduction
This blog post is about a small tip that may make working with WCF servicehost a bit easier, if you have lots of services and you need to quickly host them for testing.
Recently, I encountered a situation where we had to create multiple service host quickly for testing. Here is the code snippet which is pretty self explanatory. You can put this code in your service host which in this case is a console application.
class Program
{
static void Main(string[] args)
{
List<ServiceHost> hosts = new List<ServiceHost>();
try
{
var section = ConfigurationManager.GetSection("system.serviceModel/services")
as ServicesSection;
if (section != null)
{
foreach (ServiceElement element in section.Services)
{
var serviceType = Type.GetType(element.Name);
var host = new ServiceHost(serviceType);
hosts.Add(host);
host.Open();
}
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
foreach (ServiceHost host in hosts)
{
if (host.State == CommunicationState.Opened)
{
host.Close();
}
else
{
host.Abort();
}
}
}
}
}
I hope you find this useful. You can make this as a Windows service if required.