Getting Windows service ServiceName in .Net 5/Core

Viewed 405

I have some old Windows services written in .Net Framework that I'm rewriting in .Net 5. Everything works as it should with .UseWindowsService but one thing.

The problem is that these services has several registered services based on the same codebase, i.e. they are fetching their settings based on the ServiceName when starting up. I have written a custom IConfigurationProvider but my problem is getting the current ServiceName.

In 'Net Framework I used the ManagementObjectSearcher to get the ServiceName from the ProcessId.

            ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Service where ProcessId  = " + Environment.ProcessId);

        foreach (var item in mos.Get())
        {
            pair.Key = item["name"].ToString();
            pair.Value = item["displayname"].ToString();
        }

But in Core/5 it seems that the service isn't actually started yet, i.e. has ProcessId 0 in Win32_Service and won't be found that way.

Is there a better/working way to get the ServiceName to use in Host.CreateDefaultBuilder? I have .useWindowsService() as the first item and trying to get the ServiceName in "configuration.AddCustomConfiguration"?

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureAppConfiguration((hostingContext, configuration) =>
            {
                configuration.Sources.Clear();
                configuration.AddEnvironmentVariables();
                IHostEnvironment env = hostingContext.HostingEnvironment;
                configuration.AddCustomConfiguration();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.UseStaticWebAssets();
            })
            .UseNLog();

Regards Kristian

0 Answers
Related