WCF 経由でサービスを公開するアプリケーションを作成しています。このサービスは自己ホスト型 (コンソール アプリ) であり、Singleton インスタンスを使用する必要があります。サービス実装で属性を使用せずに、サービス構成でシングルトンを指定する方法を見つけようとしています。属性なしでコードでシングルトンを指定することは可能ですか?
ありがとう、エリック
WCF 経由でサービスを公開するアプリケーションを作成しています。このサービスは自己ホスト型 (コンソール アプリ) であり、Singleton インスタンスを使用する必要があります。サービス実装で属性を使用せずに、サービス構成でシングルトンを指定する方法を見つけようとしています。属性なしでコードでシングルトンを指定することは可能ですか?
ありがとう、エリック
web.configこれをまたはに移動したい場合app.configは、カスタムのBehaviorExtensionElementandを使用して移動できIServiceBehaviorます。
実際にはIServiceBehavior、構成から列挙型に値を解析して設定します(@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;
}
}
extension 要素を使用すると、config からプルして に渡すことができます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"/>