遵循样本压缩 http://msdn.microsoft.com/en-us/library/ms751458.aspx由微软。我已将编码器、编码器工厂和绑定元素添加到我的解决方案中。与他们的示例的不同之处在于,我们不通过配置文件(要求)注册端点,而是使用自定义服务主机工厂。
服务主机:
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
if (host.Description.Endpoints.Count == 0)
{
host.AddDefaultEndpoints();
}
host.Description.Behaviors.Add(new MessagingErrorHandler());
return host;
}
因此,我尝试的是将自定义绑定添加到我的端点,但要使用绑定注册该端点,看起来我必须使用AddServiceEndpoint
但这需要一个未知的接口。我知道我可以获得 serviceType 实现的所有接口并执行getInterfaces()[0]
,但这对我来说似乎是一种不安全的方法。
那么有没有一种方法可以使用自定义绑定注册我的端点而不知道接口,或者是否有我应该采取的更好的方法。
我尝试添加自定义绑定:
CustomBinding compression = new CustomBinding();
compression.Elements.Add(new GZipMessageEncodingBindingElement());
foreach (var uri in baseAddresses)
{
host.AddServiceEndpoint(serviceType, compression, uri);//service type is not the interface and is causing the issue
}
您的自定义绑定需要一个传输绑定元素;目前您只有一个消息编码绑定元素。您可能需要添加一个HttpTransportBindingElement
也到您的自定义绑定:
CustomBinding compression = new CustomBinding(
new GZipMessageEncodingBindingElement()
new HttpTransportBindingElement());
至于从服务类型查找接口,没有内置逻辑。 WebServiceHostFactory 中使用的逻辑类似于下面所示的逻辑(此代码深入 1 继承/实现级别,但理论上您也可以更深入。
private Type GetContractType(Type serviceType)
{
if (HasServiceContract(serviceType))
{
return serviceType;
}
Type[] possibleContractTypes = serviceType.GetInterfaces()
.Where(i => HasServiceContract(i))
.ToArray();
switch (possibleContractTypes.Length)
{
case 0:
throw new InvalidOperationException("Service type " + serviceType.FullName + " does not implement any interface decorated with the ServiceContractAttribute.");
case 1:
return possibleContractTypes[0];
default:
throw new InvalidOperationException("Service type " + serviceType.FullName + " implements multiple interfaces decorated with the ServiceContractAttribute, not supported by this factory.");
}
}
private static bool HasServiceContract(Type type)
{
return Attribute.IsDefined(type, typeof(ServiceContractAttribute), false);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)