我需要在WCF服务中自定义每个方法 - 添加日志记录。
因此,我在创建服务主机时为每个操作安装了一个专用的操作行为:
public class CoreServiceHostFactory : ServiceHostFactory
{
#region Overrides of ServiceHostFactory
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
var operationBehavior = new WcfOperationBehavior();
host.Description.Endpoints
.SelectMany(e => e.Contract.Operations)
.ForEach(o => o.Behaviors.Add(operationBehavior));
return host;
}
#endregion
}
它在本地工作,但在QA中部署时失败
无法将值添加到集合中,作为集合 已包含相同类型的项目: ......仅限此系列 支持每种类型的一个实例。参数名称:item
web.config的相关部分是:
<services>
<service name="DeviceServices.DeviceService" behaviorConfiguration="SLDeviceServices.ServiceBehavior">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="StandardBindingSSL" contract="DeviceServices.IDeviceService">
</endpoint>
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="StandardBinding" contract="DeviceServices.IDeviceService">
</endpoint>
</service>
<service name="DeviceServices.DeviceServiceJSON" behaviorConfiguration="SLDeviceServices.ServiceBehavior">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="StandardBindingSSL" contract="DeviceServices.DeviceServiceJSON" behaviorConfiguration="DeviceServices.JSONDeviceServiceBehavior">
</endpoint>
<endpoint address="" binding="webHttpBinding" bindingConfiguration="StandardBinding" contract="DeviceServices.DeviceServiceJSON" behaviorConfiguration="DeviceServices.JSONDeviceServiceBehavior">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SLDeviceServices.ServiceBehavior">
<serviceMetadata httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="DeviceServices.JSONDeviceServiceBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
我不明白是什么问题。任何人吗?
答案 0 :(得分:1)
我找到了根本原因。在QA中,服务有两个端点 - http和https,但两者都绑定到同一个Contract。
因此代码
host.Description.Endpoints
.SelectMany(e => e.Contract.Operations)
.ForEach(o => o.Behaviors.Add(operationBehavior));
两次遍历同一份合同。修复是:
host.Description.Endpoints
.Select(e => e.Contract)
.Distinct()
.SelectMany(c => c.Operations)
.ForEach(o => o.Behaviors.Add(operationBehavior));
答案 1 :(得分:0)
访问多个服务时出现的问题。 添加操作行为时需要检查重复项
host.Description.Endpoints
.Select(e => e.Contract)
.Distinct()
.SelectMany(c => c.Operations)
.ForEach(o =>
{
if(o.Behaviors.Any(x=> x.GetType().Equals(typeof(WcfOperationBehavior))))
{
o.Behaviors.Add(operationBehavior));
}
});