如何在1个Windows服务中托管2个WCF服务?
时间:2020-03-05 18:50:49 来源:igfitidea点击:
我有一个WCF应用程序,该应用程序具有两个我要使用net.tcp托管在单个Windows服务中的服务。我可以很好地运行这两个服务,但是一旦我将它们都放入Windows Service,就只能加载第一个服务。我确定正在调用第二个服务ctor,但是OnStart永远不会触发。这告诉我WCF在加载第二个服务时发现了问题。
使用net.tcp我知道我需要打开端口共享并在服务器上启动端口共享服务。这一切似乎都工作正常。我曾尝试将服务放在不同的tcp端口上,但仍然没有成功。
我的服务安装程序类如下所示:
[RunInstaller(true)] public class ProjectInstaller : Installer { private ServiceProcessInstaller _process; private ServiceInstaller _serviceAdmin; private ServiceInstaller _servicePrint; public ProjectInstaller() { _process = new ServiceProcessInstaller(); _process.Account = ServiceAccount.LocalSystem; _servicePrint = new ServiceInstaller(); _servicePrint.ServiceName = "PrintingService"; _servicePrint.StartType = ServiceStartMode.Automatic; _serviceAdmin = new ServiceInstaller(); _serviceAdmin.ServiceName = "PrintingAdminService"; _serviceAdmin.StartType = ServiceStartMode.Automatic; Installers.AddRange(new Installer[] { _process, _servicePrint, _serviceAdmin }); } }
而且两种服务看起来都很相似
class PrintService : ServiceBase { public ServiceHost _host = null; public PrintService() { ServiceName = "PCTSPrintingService"; CanStop = true; AutoLog = true; } protected override void OnStart(string[] args) { if (_host != null) _host.Close(); _host = new ServiceHost(typeof(Printing.ServiceImplementation.PrintingService)); _host.Faulted += host_Faulted; _host.Open(); } }
解决方案
回答
我们可能只需要2个服务主机。
_host1和_host2.
回答
如果要一个Windows服务启动两个WCF服务,则需要一个具有两个ServiceHost实例的ServiceInstaller,这两个实例都通过(单个)OnStart方法启动。
通常,当我们选择在Visual Studio中创建新的Windows服务时,我们可能希望遵循模板代码中的ServiceInstaller模式,这是一个很好的起点。
回答
在此MSDN文章上建立服务,并创建两个服务主机。
但是,我们可以直接将每个服务主机分解为所需的多个类,以定义要运行的每个服务,而不必直接调用每个服务主机:
internal class MyWCFService1 { internal static System.ServiceModel.ServiceHost serviceHost = null; internal static void StartService() { if (serviceHost != null) { serviceHost.Close(); } // Instantiate new ServiceHost. serviceHost = new System.ServiceModel.ServiceHost(typeof(MyService1)); // Open myServiceHost. serviceHost.Open(); } internal static void StopService() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } } };
在Windows服务主机的主体中,调用不同的类:
// Start the Windows service. protected override void OnStart( string[] args ) { // Call all the set up WCF services... MyWCFService1.StartService(); //MyWCFService2.StartService(); //MyWCFService3.StartService(); }
然后,我们可以将任意数量的WCF服务添加到一个Windows服务主机。
REMEBER也可以调用stop方法。