diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs index 6e4c43416b32d6..3180364b897e4b 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdHostBuilderExtensions.cs @@ -115,7 +115,17 @@ private static void AddSystemdLifetime(IServiceCollection services) // systemd-style integration (for example, when NOTIFY_SOCKET is set or the process // is detected as a systemd service). #pragma warning disable CA1416 // Validate platform compatibility - services.AddSingleton(); + services.AddSingleton(_ => + { + // Construct the notifier first so it reads (and normalizes) NOTIFY_SOCKET, then + // clear the env var so child processes don't inherit it and accidentally notify + // the parent's service manager. Done inside the DI factory so SystemdNotifier + // construction stays lazy and the env var is only mutated when hosting is + // actually wired up. + var notifier = new SystemdNotifier(); + Environment.SetEnvironmentVariable(SystemdConstants.NotifySocket, null); + return notifier; + }); services.AddSingleton(); #pragma warning restore CA1416 // Validate platform compatibility diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdNotifier.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdNotifier.cs index 8a183fd04cd0b5..ae7a9ac08f1f25 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdNotifier.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdNotifier.cs @@ -65,11 +65,6 @@ public void Notify(ServiceState state) return null; } - // Because this method is called on Notifier construction, the envvar is cleared when the Host is built - // (IHostLifetime depends on ISystemdNotifier). This prevents child processes from inheriting the socket - // and interfering with service manager notifications. - Environment.SetEnvironmentVariable(SystemdConstants.NotifySocket, null); - // Support abstract socket paths. if (socketPath[0] == '@') {