繁体   English   中英

如何检查上下文是 Windows 服务还是控制台应用程序

[英]How to check if the context is a Windows Service or a Console Application

填补空白:

如果 DLL 上的一段代码从不同的上下文中使用,并且我们需要确定我们在哪个上下文上运行,我们必须使用:

Web 应用程序-> System.Web.HttpContext.Current != null

WCF Web 服务-> System.ServiceModel.Operationcontext.Current != null

视窗服务 || 控制台应用程序-> ______________________________________________________

另外,如果您知道检查前两个之一的更好选择,请告诉我们。

关于它可能与另一个问题重复的事实:我不需要区分 Windows 服务和控制台应用程序(用户交互与否)。

编辑:为什么我需要那个?

我需要从可以在不同上下文中运行的库中打开正在运行的应用程序的配置文件。 这是我目前拥有的:

Configuration appConfig = null;

if (System.Web.HttpContext.Current != null || System.ServiceModel.OperationContext.Current != null)
{
    // The call was originated from a web application or from a WCF web service.
    appConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
    // The call may have been originated from a console application or a windows service.
    // THE ANSWER TO MY SO QUESTION WOULD ALLOW ME TO INSERT AN IF HERE!!
    appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}

else 部分假设我在类似 exe 的环境(Windows 服务、控制台应用程序)上运行。 我想包含一个if以确保OpenExeConfiguration不会抛出异常。

我已经考虑过使用 try 块,但这不适合我的情况。

我认为这是一个非常脆弱的结构,但是如果您检查AppDomain.CurrentDomain.SetupInformation.ConfigurationFile是否以字符串web.config结尾,您可以验证当前应用程序域是否在 Web 服务器中运行,然后您可以调用System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 获取Configuration实例。

反之亦然:如果它以.exe.config结尾,您可以使用ConfigurationManager.OpenExeConfiguration(...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM