.NET Core 的服务检测 [英] Service detection for .NET Core
问题描述
您能否为 .NET Core
推荐一种方法,它能够在运行时检测代码是否在服务中执行?
Could you please suggest a method for .NET Core
which is able to detect in runtime whether the code is executed within a service or not?
我有 .NET Framework
的工作代码,但我认为无法移植它,因为它基于 .NET Core 1.1
中不可用的属性.
I have the working code for .NET Framework
but I think it is impossible to port it because it is based on properties unavailable in .NET Core 1.1
.
推荐答案
这不能通过 .NET Core 中的公共托管 API 直接实现.Environment.UserInteractive
默认为固定值,并检查以测试 stdout 的连接方式在各种情况下也会产生意想不到的结果(例如带有 & 没有 stdout 连接的子进程).
This is not directly possible with public managed APIs in .NET Core. Environment.UserInteractive
is defaulted to a fixed value and checks to test how stdout is wired up can yield unexpected results as well for various situations (like subprocesses with & without stdout wiring).
In my sample implementation for service hosting APIs i ended up requiring the service registration to add a command line argument (--run-as-service
) when the executable is installed as a windows service (in this app, wen called with --register-service
). A lot of non-.net applications work this way, including docker.
这篇关于.NET Core 的服务检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!