簡體   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