我正在编写一个通过WCF公开服务的应用程序。该服务是自托管的(控制台应用程序),需要使用Singleton实例。我试图找出如何在服务配置中指定单例,而不使用使用服务实现上的属性。是否可以在没有属性的代码中指定单例?
谢谢, 埃里克
答案 0 :(得分:22)
您可以将服务实例传递给 ServiceHost
constructor,而不是传递类型。在这种情况下,您传递的实例将用作单例。
修改强>
我以前的解决方案不起作用。向ServiceHost
构造函数提供实例仍然需要ServiceBehaviorAttribute
InstanceContextMode.Single
。但是这个应该有效:
var host = new ServiceHost(typeof(Service));
var behavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
behavior.InstanceContextMode = InstanceContextMode.Single;
host.Open();
即使您未指定 ServiceBehaviorAttribute
,也包括在内,因此您只需要获取它并更改默认值。
答案 1 :(得分:0)
如果您想将其移至web.config
或app.config
,则可以使用自定义BehaviorExtensionElement
和IServiceBehavior
:
IServiceBehavior
实际上会将config中的值解析为枚举并设置它(遵循@ Ladislav的回答):
public class InstanceContextServiceBehavior : IServiceBehavior
{
InstanceContextMode _contextMode = default(InstanceContextMode);
public InstanceContextServiceBehavior(string contextMode)
{
if (!string.IsNullOrWhiteSpace(contextMode))
{
InstanceContextMode mode;
if (Enum.TryParse(contextMode, true, out mode))
{
_contextMode = mode;
}
else
{
throw new ArgumentException($"'{contextMode}' Could not be parsed as a valid InstanceContextMode; allowed values are 'PerSession', 'PerCall', 'Single'", "contextMode");
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
var behavior = serviceDescription.Behaviors.Find<ServiceBehaviorAttribute>();
behavior.InstanceContextMode = _contextMode;
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
return;
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
return;
}
}
扩展元素允许您从配置中提取它并将其传递给IServiceBehavior
:
public class InstanceContextExtensionElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get
{
return typeof(InstanceContextServiceBehavior);
}
}
protected override object CreateBehavior()
{
return new InstanceContextServiceBehavior(ContextMode);
}
const object contextMode = null;
[ConfigurationProperty(nameof(contextMode))]
public string ContextMode
{
get
{
return (string)base[nameof(contextMode)];
}
set
{
base[nameof(contextMode)] = value;
}
}
}
然后您可以在配置中注册并使用它:
<extensions>
<behaviorExtensions>
<add name="instanceContext" type="FULLY QUALFIED NAME TO CLASS"/>
</behaviorExtensions>
</extensions>
...
<serviceBehaviors>
<behavior name="Default">
<instanceContext contextMode="Single"/>