Suppose you are controlling a set of industrial devices through WCF services. Each device will host their own WCF service. Let's call this generic WCF service MyDeviceController
I want to write once and deploy on each device. However for testing purposes, I also want to deploy all the WCF instances on one local box.
Given this context, how do you deploy multiple instances of a WCF services both local and multiple boxes?
If I am being too vague, please help me clarify my question. I more than happy to edit it.
I wrote an easy to handle service host once:
public static class SimpleServiceHost<ServiceContract, Service>
{
private static Thread hostThread;
private static object _lockStart = new object();
private static object _lockStop = new object();
public static bool IsRunning { get; set; }
public static void WaitUntilIsStarted()
{
while (!IsRunning)
{
Thread.Sleep(100);
}
}
public static void Start(Binding binding, string host, string path, int port)
{
var serviceUri = new UriBuilder(binding.Scheme, host, port, path).Uri;
Start(binding, serviceUri);
}
public static void Start(Binding binding, Uri serviceUri)
{
lock (_lockStart)
{
if (hostThread == null || !hostThread.IsAlive)
{
hostThread = new System.Threading.Thread(() =>
{
using (ServiceHost internalHost = new ServiceHost(typeof(Service)))
{
internalHost.Faulted += new EventHandler((o, ea) =>
{
IsRunning = false;
throw new InvalidOperationException("The host is in the faulted state!");
});
internalHost.AddServiceEndpoint(typeof(ServiceContract), binding, serviceUri);
try
{
internalHost.Open();
IsRunning = true;
}
catch
{
IsRunning = false;
}
while (true)
Thread.Sleep(100);
}
});
}
hostThread.Start();
}
}
public static void Stop()
{
lock (_lockStart)
{
lock (_lockStop)
{
hostThread.Abort();
IsRunning = false;
}
}
}
}
So if you are willing to use multiple contracts you can just call like this:
SimpleServiceHost<IService, Service>.Start(new BasicHttpBinding(), "localhost", "TestService", 8086);
Otherwise make my service host work like a factory and return instances when calling start. You probably will need to enhance the class to fulfill your requirements. But you save a lot of code especially when you need to dynamically host several services ;-)
Regards Jan
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.