实例化多个WCF服务

时间:2013-09-04 18:53:35

标签: c# wcf deployment instance

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

鉴于此上下文,您如何在本地和多个框中部署WCF服务的多个实例?

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

1 个答案:

答案 0 :(得分:0)

我写了一个易于处理的服务主机:

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;
            }
        }
    }

}

因此,如果您愿意使用多个合同,您可以这样打电话:

SimpleServiceHost<IService, Service>.Start(new BasicHttpBinding(), "localhost", "TestService", 8086);

否则,让我的服务主机像工厂一样工作,并在调用start时返回实例。您可能需要增强课程以满足您的要求。但是,您可以节省大量代码,尤其是当您需要动态托管多个服务时; - )

此致 扬