Programmatically set InstanceContextMode

前端 未结 3 1051
死守一世寂寞
死守一世寂寞 2021-02-06 21:52

Is there a way to do this ...

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

...pro

3条回答
  •  萌比男神i
    2021-02-06 22:00

    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();
            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();
        behaviour.InstanceContextMode = InstanceContextMode.Single;
    }
    _host = _host ?? new HttpServiceHost(typeof (TApi), baseUri);
    

提交回复
热议问题