我的任务是将数十个 WCF 服务转移到单个 Windows 服务。我使用 Windows 服务模板创建了一个 Windows 服务,并将以下代码添加到 ServiceHostController:
public partial class ServiceHostController : ServiceBase
{
private List<ServiceHost> serviceHosts;
public ServiceHostController()
{
InitializeComponent();
this.ServiceName = "WCFServices";
this.CanStop = true;
this.AutoLog = true;
}
protected override void OnStart(string[] args)
{
if (serviceHosts != null)
{
foreach (var service in serviceHosts)
{
service.Close();
}
}
InitializeServices();
foreach (var service in serviceHosts)
{
service.Open();
}
}
protected override void OnStop()
{
if (serviceHosts != null)
{
foreach (var service in serviceHosts)
{
service.Close();
}
serviceHosts.Close(); = null;
}
foreach (var service in serviceHosts)
{
service.Close();
}
}
private void InitializeServices()
{
serviceHosts = new List<ServiceHost>()
{
new ServiceHost(typeof(WCFService1)),
new ServiceHost(typeof(WCFService2)),
// add dozens of services here
};
}
}
除了不遵循此处不要重复自己的规则(实际代码不同)之外,我应该如何在 Windows 服务代码中托管这些 WCF 服务?