如何设置ServiceHostingEnvironment.AspNetCompatibilityEnabled = true在code(未配置)的.NET / C# [英] How to set ServiceHostingEnvironment.AspNetCompatibilityEnabled = true in Code (not in config) .NET/C#

查看:1507
本文介绍了如何设置ServiceHostingEnvironment.AspNetCompatibilityEnabled = true在code(未配置)的.NET / C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,从访问HttpContext.Current使用,在一个RESTful WCF服务。我知道我能做到这一点通过添加以下配置:

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)]

下面是我的问题,我需要旋服务的一个实例,在code单元测试,所以我不能使用配置文件来指定服务bebaviours等。 此刻我的code样子如下,但尽管淘网我已经无法工作了我如何建立一个ServiceHostingEnvironment类和AspNetCompatibilityEnabled属性设置为true,而无需使用配置,任何人都可以帮忙吗?

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();

任何帮助是提前多少AP preciated和感谢。

Any help is much appreciated and thanks in advance.

推荐答案

考虑分解出明确使用HttpContext.Current的接口后,你可以在单元测试过程存根出。

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

HttpContext.Current只被定义在WCF服务的一个asp.net web应用程序中托管反正 - 如果有一天你需要承载它作为一个普通的WCF服务,HttpContext.Current是不会用。

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.

这篇关于如何设置ServiceHostingEnvironment.AspNetCompatibilityEnabled = true在code(未配置)的.NET / C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆