我在Windows服务中托管了一个WCF进程。 我想知道我是否可以安全地拥有多个WCF进程,这些进程在同一个Windows服务中托管不同的东西。 我不得不担心端口吗? 我正在使用mex端点
答案 0 :(得分:8)
编辑:所以似乎正在修剪我冗长的代码/配置示例,所以这里有一个完整的解释:http://thegrenade.blogspot.com/2009/08/hosting-multiple-wcf-services-under.html
以下是一个可以帮助您前进的示例:
class Program {
static void Main() {
if (Environment.UserInteractive) {
ServiceManager serviceManager = new ServiceManager();
serviceManager.OpenAll();
Console.ReadKey();
serviceManager.CloseAll();
}
else
ServiceBase.Run(new WindowsService());
}
}
public class WindowsService : ServiceBase
{
public static string WindowsServiceName = "Windows Service Name";
public static string WindowsServiceDescription = "Windows Service Description";
public static string WindowsServiceUsername = @".\username";
public static string WindowsServicePassword = "password";
private readonly ServiceManager serviceManager = new ServiceManager();
private readonly IContainer components = new Container();
protected override void Dispose(bool disposing) {
if (serviceManager != null) serviceManager.CloseAll();
if (disposing && (components != null)) components.Dispose();
base.Dispose(disposing);
}
public WindowsService() {
ServiceName = WindowsServiceName;
CanStop = true;
}
protected override void OnStart(string[] args) {
base.OnStart(args);
serviceManager.OpenAll();
}
protected override void OnStop() {
serviceManager.CloseAll();
base.OnStop();
}
}
public class ServiceManager {
readonly List<ServiceHost> serviceHosts = new List<ServiceHost>();
public void OpenAll() {
OpenHost<Service1>();
OpenHost<Service2>();
...
}
public void CloseAll() {
foreach (ServiceHost serviceHost in serviceHosts)
serviceHost.Close();
}
private void OpenHost<T>() {
Type type = typeof(T);
ServiceHost serviceHost = new ServiceHost(type);
serviceHost.Open();
serviceHosts.Add(serviceHost);
}
}
/// <remarks>
/// Enables application to be installed as a Windows Service by running InstallUtil
/// </remarks>
[RunInstaller(true)]
public class WcfServiceHostInstaller : Installer {
public WcfServiceHostInstaller() {
Installers.Add(new ServiceInstaller
{
StartType = ServiceStartMode.Automatic,
ServiceName = WindowsService.WindowsServiceName,
Description = WindowsService.WindowsServiceDescription
});
Installers.Add(new ServiceProcessInstaller { Account = ServiceAccount.User, Username = WindowsService.WindowsServiceUsername, Password = WindowsService.WindowsServicePassword });
}
}
和一些配置
我为不同的服务使用不同的端口,但您没有。
...
答案 1 :(得分:3)
是的,你可以。我在我的项目中正在做这件事,在我的Windows服务中托管三个单独的WCF服务。只需确保每个WCF端点(即地址/绑定/合同元组)都是唯一的。
答案 2 :(得分:1)
看看这个Run WCF ServiceHost with multiple contracts它不是你要求的,但可能有用。
使用它加上ServiceBehaviour属性的InstanceContextMode属性以及配置Service throttling的能力,你应该能够得到你想要的东西。
答案 3 :(得分:1)
与@Matt一样,我也是在这个链接的帮助下完成的。