使用命名管道的WCF 服务。我现在这样做是为了在一些 WF4 活动的设计表面和 Visual Studio 扩展之间进行交流。
做起来很简单。我无法显示所有代码,因为其中一些代码包含在控制打开和关闭通道的助手中,但定义非常简单,并且全部在代码中完成。
你只需要定义一个绑定
var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
binding.ReceiveTimeout = TimeSpan.FromMinutes(1);
创建您的频道
var channelFactory = new ChannelFactory<IServiceInterface>(binding, endpointAddress);
并且您必须确保端点地址在客户端和服务器中都保证相同,它们共享相同的进程但存在于不同的 AppDomain 中。一种简单的方法是将地址范围限定为进程 ID...
private const string AddressFormatString =
"net.pipe://localhost/Company/App/HostType/{0}";
private static string _hostAddress;
public static string HostAddress()
{
if (_hostAddress == null)
_hostAddress = string.Format(
AddressFormatString,
Process.GetCurrentProcess().Id);
return _hostAddress;
}
您将有两个实际副本(一个在客户端 appdomain 中,一个在 addin appdomain 中),但由于它们都在同一个进程中,因此主机地址保证在两者中相同,您不会遇到问题您同时加载了多个 VS 实例(没有可怕的运行对象表,谢谢)。
我将此地址代码保存在基本主机类中。打开主机频道也很简单:
Host = new ServiceHost(this, new Uri(HostAddress()));
var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
Host.AddServiceEndpoint(typeof(IServiceInterface), binding, HostAddress());
Host.Open();