0

假设您正在通过 WCF 服务控制一组工业设备。每个设备都将托管自己的 WCF 服务。让我们将这个通用 WCF 服务称为MyDeviceController我想编写一次并部署在每个设备上。但是出于测试目的,我还想在一个本地机器上部署所有 WCF 实例。

鉴于这种情况,您如何部署本地和多个盒子的 WCF 服务的多个实例?

如果我太模糊,请帮助我澄清我的问题。我非常乐意编辑它。

4

1 回答 1

0

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

于 2013-09-05T06:35:08.800 回答