c# – 作为自己的客户端的服务
考虑这种情况:
> WCF服务已启动并正在运行. 我现在所做的是为同一服务添加服务引用,并在服务配置文件中添加一个额外的端点客户端.在net.tcp上工作. 它工作正常,但我在某处读到你可以使用“进程中”托管来连接到服务而不使用代理.这样您就可以摆脱配置并获得更清晰的代码. 因此,使用相应的配置设置而不是这个: DeliveryOwnClient.DeliveryClient deliveryObject = new DeliveryOwnClient.DeliveryClient("netTcpDeliveryService"); 我想在没有任何配置的情况下使用它: IDelivery deliveryObject = InProcessFactory.CreateInstance<DeliveryService.Delivery,IDelivery>(); 但是这引发了一个异常,“带有合同的http://localhost:8003/DeliveryService的ChannelDispatcher”IMetadataExchange“无法打开IChannelListener.对于Uri net.tcp:// localhost:9003 / DeliveryService已经存在注册” CreateInstance的实现如下所示: ServiceHost host = new ServiceHost(typeof(S)); string address = "net.pipe://" + Environment.MachineName + "/" + Guid.NewGuid(); host.AddServiceEndpoint(typeof(I),Binding,address); host.Open(); 所以我添加了一个net.pipe baseaddress,它失败了,因为net.tcp上已经有了一些东西. **编辑** 至少弄清楚为什么会发生这种情况. 该服务在app.config中配置了两个baseaddresses <service name="DeliveryService.Delivery"> <endpoint binding="netTcpBinding" contract="DeliveryService.IDelivery"/> <host> <baseAddresses> <add baseAddress="http://localhost:8003/DeliveryService" /> <add baseAddress="net.tcp://localhost:9003/DeliveryService" /> </baseAddresses> </host> </service> 当主机构建时 ServiceHost host = new ServiceHost(typeof(S)); 它在配置文件中找到该部分并自动添加net.tcp和http基地址. 所以我想我的问题变成了:是否有可能在没有读取app.config的情况下构建ServiceHost? 解决方法
周杰伦设法搞清楚了! ServiceHost派生自ServiceHostBase,该类具有名为ApplyConfiguration的虚函数.所以我创建了一个派生自ServiceHost的类并重写了ApplyConfiguration …并将其保留为空.
class ServiceHostNoConfig<S> : ServiceHost where S : class { public ServiceHostNoConfig(string address) { UriSchemeKeyedCollection c = new UriSchemeKeyedCollection(new Uri(address)); InitializeDescription(typeof(S),c); } public new void InitializeDescription(Type serviceType,UriSchemeKeyedCollection baseAddresses) { base.InitializeDescription(serviceType,baseAddresses); } protected override void ApplyConfiguration() { } } 像这样使用它: ServiceHost host = new ServiceHostNoConfig<S>(address); host.AddServiceEndpoint(typeof(I),address); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |