我有大量 WCF 服务,这些服务托管在 IIS 上。
所有这些服务都具有相同的system.serviceModel
配置。它们都具有相同的绑定配置,行为配置,唯一不同的是服务的合同,它被放置在不同的自定义配置文件中以供不同的使用。
现在,我在system.serviceModel
部分所做的每项更改都需要在所有服务中完成并且令人讨厌。
由于我使用自定义C#代码创建 WCF 客户端并更新它们以适应服务,我正在考虑以某种方式通过C#代码以某种方式创建服务system.serviceModel
(并且每个更改都将是dll更新或其他内容。)
所以,我想可以通过代码创建服务。
我也猜测可以通过创建自定义ServiceHostFactory
来完成,但我无法找到可以选择服务绑定的地方。
实现这样的目标的最佳途径是什么?
答案 0 :(得分:2)
来自msdn的代码示例似乎适合您的问题:我将其复制到此处以供参考。
绑定
// Specify a base address for the service
String baseAddress = "http://localhost/CalculatorService";
// Create the binding to be used by the service.
BasicHttpBinding binding1 = new BasicHttpBinding();
和端点
using(ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.AddServiceEndpoint(typeof(ICalculator),binding1, baseAddress);
现在,这是另一个带有ServiceFactory
的examplepublic class ServiceHostFactory :
System.ServiceModel.Activation.ServiceHostFactory
{
protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
host.Description.Behaviors.Add(ServiceConfig.ServiceMetadataBehavior);
ServiceConfig.Configure((ServiceDebugBehavior)host.Description.Behaviors[typeof(ServiceDebugBehavior)]);
return host;
}
}
在代码中完成配置:
public static class ServiceConfig
{
public static Binding DefaultBinding
{
get
{
var binding = new BasicHttpBinding();
Configure(binding);
return binding;
}
}
public static void Configure(HttpBindingBase binding)
{
if (binding == null)
{
throw new ArgumentException("Argument 'binding' cannot be null. Cannot configure binding.");
}
binding.SendTimeout = new TimeSpan(0, 0, 30, 0); // 30 minute timeout
binding.MaxBufferSize = Int32.MaxValue;
binding.MaxBufferPoolSize = 2147483647;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
}
public static ServiceMetadataBehavior ServiceMetadataBehavior
{
get
{
return new ServiceMetadataBehavior
{
HttpGetEnabled = true,
MetadataExporter = {PolicyVersion = PolicyVersion.Policy15}
};
}
}
public static ServiceDebugBehavior ServiceDebugBehavior
{
get
{
var smb = new ServiceDebugBehavior();
Configure(smb);
return smb;
}
}
public static void Configure(ServiceDebugBehavior behavior)
{
if (behavior == null)
{
throw new ArgumentException("Argument 'behavior' cannot be null. Cannot configure debug behavior.");
}
behavior.IncludeExceptionDetailInFaults = true;
}
}