Programmatically set InstanceContextMode

筅森魡賤 提交于 2019-12-03 04:13:01
Antony Scott

I'm answering my own question as I've found a solution in another answer on stackoverflow, and I think stackoverflow is a great place to search without even having to ask a question, so hopefully I will add to that richness by answering my own question with a link to the other answer and not just closing my own question.

My code now looks like this ...

public HttpWebService(string baseUri, string acceptType, TApi serviceInstance = null)
{
    _baseUri = baseUri;
    _acceptType = acceptType.ToLower();

    if (serviceInstance != null)
    {
        _host = new HttpServiceHost(serviceInstance, baseUri);
        var behaviour = _host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
        behaviour.InstanceContextMode = InstanceContextMode.Single;
    }
    _host = _host ?? new HttpServiceHost(typeof (TApi), baseUri);

    _host.Open();
    _client = new HttpClient();
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_acceptType));
}

I changed this ...

_host = serviceInstance == null
            ? new HttpServiceHost(typeof (TApi), baseUri)
            : new HttpServiceHost(serviceInstance, baseUri);

... to this ...

if (serviceInstance != null)
{
    _host = new HttpServiceHost(serviceInstance, baseUri);
    var behaviour = _host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
    behaviour.InstanceContextMode = InstanceContextMode.Single;
}
_host = _host ?? new HttpServiceHost(typeof (TApi), baseUri);

Even though the original answer contains the solution it is Just a straight answer to the question

ServiceHost host = new ServiceHost(typeof(YourService)); //Or get the Servicehost
((ServiceBehaviorAttribute)host.Description.
Behaviors[typeof(ServiceBehaviorAttribute)]).InstanceContextMode 
= InstanceContextMode.Single;

We can also use the ServiceBehaviourAttribute at the Service class in order to set the InstanceContextMode as below:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyService : IMyService
{
//service code
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!