充当自己的客户端的服务



考虑这个场景:

  1. WCF服务已启动并正在运行
  2. 该服务需要每隔一段时间调用一次自己

我现在所做的是向同一服务添加一个服务引用,并在服务配置文件中添加一个额外的endpoint+客户端。在net.tcp.上工作

它运行良好,但我在某个地方读到,您可以使用"进程中"托管连接到服务,而无需使用代理。通过这种方式,您可以摆脱配置,并拥有更干净的代码。

因此,与此不同的是,提供配置设置:

DeliveryOwnClient.DeliveryClient deliveryObject = new DeliveryOwnClient.DeliveryClient("netTcpDeliveryService");

我想在没有任何配置的情况下使用这个:

IDelivery deliveryObject = InProcessFactory.CreateInstance<DeliveryService.Delivery, IDelivery>();

但这引发了一个例外,即"ChannelDispatcherhttp://localhost:8003/DeliveryService合约为"IMetadataExchange"的无法打开IChannelListener。Uri网络已存在注册。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基地址,但它失败了,因为已经有一些东西在net.tcp上运行。

**编辑**

至少弄清楚了为什么会发生这种情况。

该服务在app.config中配置为具有两个基地址

<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基地址。我加了net.pipe,但没关系。当服务打开时,它发现net.tcp已经在运行,所以它不会继续。

所以我想我的问题变成了:是否可以在不读取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), Binding, address);

相关内容

最新更新