微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在代码中覆盖配置文件WCF Base Addresses

我有一个WCF Windows服务,在服务的配置文件中指定了端点.
<baseAddresses>
    <add baseAddress="net.tcp://localhost:9000/MyEndpoint"/>
</baseAddresses>

一切正常.但是,在某些情况下,端口9000可能已在使用中,导致ServiceHost在open()上失效.
我需要能够在代码中覆盖配置文件中指定的认基址.例如假设环境变量包含要使用的端口号.

有没有办法以编程方式执行此操作?

在构造ServiceHost之后,我可以看到BaseAddresses属性,该属性返回从配置文件获取的Uri列表.但是,这是一个只读集合,因此不能用于更改认值.

如果我在ServiceHost构造函数中指定替换Uri,我得到

This collection already contains an
address with scheme net.tcp. There
can be at most one address per scheme
in this collection. If your service is
being hosted in IIS you can fix the
problem by setting
‘system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled’
to true or specifying
‘system.serviceModel/serviceHostingEnvironment/baseAddressprefixFilters’.

如果我创建一个CustomServiceHost并尝试设置替换基地址,我会得到相同的错误.

class CustomHost : ServiceHost
{
    public CustomHost(Type serviceType) : base (serviceType)         
    {
    }
    protected override void ApplyConfiguration()
    {
        base.ApplyConfiguration();

        this.AddBaseAddress(new Uri("net.tcp://localhost:9010/MyEndpoint"));
    }
}

我知道,如果我将配置文件基地址留空并将基地址传递给ServiceHost构造函数,那么这样可以正常工作 – 即我可以指定新的基数.但是,我想使用配置文件来指定认值(而不是硬编码).

解决方法

看看我发布的这个例子.它有一个完全通过代码配置的WCF服务的完整工作示例.您应该能够使用Environment.GetEnvironmentvariable获取端口号并将其传递给ServiceHost的构造函数

Possible to have same contract,same binding,same address,but different ports?

原文地址:https://www.jb51.cc/csharp/100157.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐