Question

Is there a way to do this ...

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

...programmatically?

The reason is that I want to pass in an instance of my service directly into my self-hosting helper class when integration testing my service.

I'm using Castle Windsor to create all my objects, which works fine when using the test web site. But I get the following error when I try to use my HttpWebService helper class ...

System.InvalidOperationException was unhandled by user code
  Message=In order to use one of the ServiceHost constructors that takes a service instance, the InstanceContextMode of the service must be set to InstanceContextMode.Single.  This can be configured via the ServiceBehaviorAttribute.  Otherwise, please consider using the ServiceHost constructors that take a Type argument.
  Source=System.ServiceModel

This is the constructor of my helper class ...

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

    _host = serviceInstance == null
                ? new HttpServiceHost(typeof (TApi), baseUri)
                : new HttpServiceHost(serviceInstance, baseUri);
    _host.Open();
    _client = new HttpClient();
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_acceptType));
}

So, I need to programmatically set the InstanceContextMode when in "integration test mode", ie - in my helper class.

I think I need to do something like this ...

if (serviceInstance != null)
{
    _host = new HttpServiceHost(serviceInstance, baseUri);
    var whatDoIDoNow = null;
    _host.Description.Behaviors.Add(whatDoIDoNow);
}

Any help/guidance would be great as I'm really stuck on this.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top