tags:

views:

1134

answers:

2

Hi all,

I have a requirement to access the HttpContext.Current from with-in a RESTful WCF service. I know I am able to achieve this by adding the following to config:

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />

and using the following attribute on my service:

[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Required)]

Here is my issue, I need to "spin up" an instance of the service in code for unit testing and therefore I cannot use config files to specify service bebaviours etc. At the moment my code looks like follows, but despite scouring the web I have been unable to work out how I set up a ServiceHostingEnvironment class and set the AspNetCompatibilityEnabled property to true without using config, can anyone help?

string serviceUrl = "http://localhost:8082/MyService.svc";

_host = new ServiceHost(typeof(MyService), new Uri[] { new Uri(serviceUrl) });

ServiceEndpoint serviceEndpoint 
    = _host.AddServiceEndpoint(typeof(IMyService), new WebHttpBinding(), string.Empty);

serviceEndpoint.Behaviors.Add(new WebHttpBehavior());

// Here's where I'm stuck, i need something like...
ServiceHostingEnvironmentSection shes = new ServiceHostingEnvironmentSection();
shes.AspNetCompatibilityEnabled = true;
_host.Add(shes);

_host.Open();

Any help is much appreciated and thanks in advance.

A: 
marc_s
Unfortunately that property has no setter.
HaggleLad
A: 

Consider factoring out the explicit use of HttpContext.Current behind an interface that you can stub out during unit testing.

HttpContext.Current is only defined when your wcf service is hosted within an asp.net web application anyway - if some day you need to host it as an ordinary wcf service, HttpContext.Current is not going to be available.

Mikkel Christensen