Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Windows Services under .NET Core 2.1 #455

Open
TimurZanagar opened this Issue Jun 12, 2018 · 30 comments

Comments

Projects
None yet
@TimurZanagar
Copy link

TimurZanagar commented Jun 12, 2018

Hi folks,

I just read the article "Hidden Gems in .NET Core 2.1" and there are some gems which should help you to migrate Topshelf to .NET Core.

Why? Microsoft released an interface called IHostingService which is packed in the NuGet.

I don't know if this is really useful, but I wanted to leave this information here for the issues:
##444
##393
##277

Here are some further links:

@phatboyg

This comment has been minimized.

Copy link
Contributor

phatboyg commented Jun 12, 2018

Thanks. The develop branch already works with .NET core, support for IHostedService might make sense at some point, just to make it easy to move services from running within ASP.NET to Topshelf.

There is also at some point likely synergy between Topshelf and the Generic ASP.NET Host effort.

@RedDeathGitHub

This comment has been minimized.

Copy link

RedDeathGitHub commented Aug 7, 2018

Do you have a timeline when a stable version, working under .NET Core 2.1, will be released?

@MartinPettit

This comment has been minimized.

Copy link

MartinPettit commented Sep 3, 2018

I would also be keen to know when this .NET Core-compatible version will be released

@phatboyg

This comment has been minimized.

Copy link
Contributor

phatboyg commented Sep 18, 2018

The prerelease packages are available now for testing. once verified, they'll be released. You can help here :)

@china-live

This comment has been minimized.

Copy link

china-live commented Sep 19, 2018

加油!

@Nekromancer

This comment has been minimized.

Copy link

Nekromancer commented Sep 19, 2018

Working great on Windows Server 2016 with .NET Core 2.1 Self-Contained app. Thanks!

@drano

This comment has been minimized.

Copy link

drano commented Sep 27, 2018

How to implement it with .NET Core 2.1 ? Could you provide an example ?

@Nekromancer

This comment has been minimized.

Copy link

Nekromancer commented Sep 27, 2018

Just use it exactly like in the .NET Framework. Start with console app and build TopShelf as in documentation. Nothing weird here

@drano

This comment has been minimized.

Copy link

drano commented Sep 27, 2018

My console app is working, but I cannot install it as a windows service. I have an error message
"Error 1053: The service did not respond to the start or control request in a timely fashion."

@Nekromancer

This comment has been minimized.

Copy link

Nekromancer commented Sep 27, 2018

Are you using latest preview nuget? Show some code so we can help

@drano

This comment has been minimized.

Copy link

drano commented Sep 27, 2018

Version: 4.1.0.175-Desktop
.NET Core: 2.1

using System;
using Topshelf;
using Topshelf.HostConfigurators;

namespace ConsoleApp1
{
    class MyService : ServiceControl
    {
        public bool Start(HostControl hostControl)
        {
            Console.WriteLine("Start");
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            Console.WriteLine("Stop");
            return true;
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
          
            var host = HostFactory.New(x =>
            {
                x.Service<MyService>();

                ConfigureService(x, "MyServices");
            });

            host.Run();
        }

        private static void ConfigureService(HostConfigurator x, string serviceName)
        {
            x.StartAutomatically();
            x.SetDisplayName(serviceName);
            x.SetServiceName(serviceName);

            x.RunAsPrompt();

            //x.UseNLog();

            x.EnableServiceRecovery(r =>
            {
                r.RestartService(0);
                r.OnCrashOnly();
                r.SetResetPeriod(1);
            });
        }
    }
}
@phatboyg

This comment has been minimized.

Copy link
Contributor

phatboyg commented Sep 27, 2018

You realize it's GA now, right? No need for a preview.

@drano

This comment has been minimized.

Copy link

drano commented Sep 27, 2018

I don’t understand. What’s mean « GA » ? My previous code is in .net core. Is it correct ?

@chrkon

This comment has been minimized.

Copy link

chrkon commented Sep 28, 2018

@Nekromancer

This comment has been minimized.

Copy link

Nekromancer commented Sep 28, 2018

RunAsPrompt is helper function for topshelf to ask for account during service install. It has nothing to do with starting a service as command line. For me your code seems fine. It's working for me. Are you publishing it to self-contained package?

@drano

This comment has been minimized.

Copy link

drano commented Sep 28, 2018

Yes, I am using a self-contained package.

When I try to install with "myservice.exe install" , then I have an error message
"An exception occurred during the Install phase.
System.PlatformNotSupportedException: Operation is not supported on this platform."

When I try to install with "sc.exe create binpath="fullpath\myservice.exe", then I start this service, I have the exception
"Error 1053: The service did not respond to the start or control request in a timely fashion."

@Nekromancer

This comment has been minimized.

Copy link

Nekromancer commented Sep 28, 2018

What operating system are you using? Can you reproduce this on another machine?

@drano

This comment has been minimized.

Copy link

drano commented Sep 28, 2018

On Windows Server 2012R2... Old version !
But, same problem with Windows server 2016

@sphiecoh

This comment has been minimized.

Copy link

sphiecoh commented Oct 11, 2018

I am getting the same exception on windows server 2016

@fabricioferreira

This comment has been minimized.

Copy link

fabricioferreira commented Oct 19, 2018

Same exception on Windows 10.
After researching a bit more, I found that part of the issue was related to the x.RunAsPrompt() call.
Down the rood, when this setup is made, later on the code will try to execute the "GetLoginInfo()" from "ServiceProcessInstaller" class, and it fails.

The code looks like this:

if (!base.Context.Parameters.ContainsKey("unattended"))
{
	throw new PlatformNotSupportedException();
	//using (ServiceInstallerDialog serviceInstallerDialog = new ServiceInstallerDialog())
	//{
	//    if (this.username != null)
	//    {
	//        serviceInstallerDialog.Username = this.username;
	//    }
	//    serviceInstallerDialog.ShowDialog();
	//    switch (serviceInstallerDialog.Result)
	//    {
	//        case ServiceInstallerDialogResult.Canceled:
	//            throw new InvalidOperationException(Res.GetString("UserCanceledInstall", base.Context.Parameters["assemblypath"]));
	//        case ServiceInstallerDialogResult.UseSystem:
	//            this.username = null;
	//            this.password = null;
	//            this.serviceAccount = ServiceAccount.LocalSystem;
	//            break;
	//        case ServiceInstallerDialogResult.OK:
	//            this.username = serviceInstallerDialog.Username;
	//            this.password = serviceInstallerDialog.Password;
	//            break;
	//    }
	//}
	//return;
}

I will take more time to inspect it a bit more, but I hope this can give a clue to the actual issue.

I said it was partial because even after I remove that setup line, the service still doesn't starts. If I run the service executable from the command line it works fine, but from the service it fails with the following message:

Error 1053: The service did not respond to the start or control request in a timely fashion.

I hope this helps!

-Cheers!

@paddydev

This comment has been minimized.

Copy link

paddydev commented Nov 8, 2018

Able to install .net core 2.1 console app as windows service using topshelf 4.1 nuget . But when i try to configure Log4net using Topshelf Log4net extension nuget and call UseLog4Net using hostconfigurator, I see the files created but not writing any logs when I run as a service. But the same works fine if i run it in local. Any help is appreciated. Thanks !

@snakefoot

This comment has been minimized.

@boekabart

This comment has been minimized.

Copy link

boekabart commented Nov 26, 2018

I'd like to confirm here that using TopShelf 4.1.0 'GA' release, I was able to target my application to netcoreapp1.1 - runtime win7-x64, and install and run it as a service, under both Windows 10 pro, as well as windows 2008R2 x64 (which doesn't even have .net 4.5.2 installed).

The only thing I had to do is specify on the command line to install as something, as our application's default is to use the popup. I didn't have to remove the RunAsPrompt code that makes that the default!

Again - I didn't have to change any code at all - just use the correct nuget package version.

Only suggestion I would have, is to maybe remove this RunAsPrompt from the public API for the non net4xx builds, as it will crash anyway. It forces you, as an app developer, to at least realise this when targeting netcoreapp.

@mtherien

This comment has been minimized.

Copy link

mtherien commented Dec 13, 2018

I am also getting this error. TopShelf 4.1.0, target app netcoreapp2.1, runtime win10-x64.

I do not have the RunAsPrompt in my code.

This is a simple service that starts a Quartz.net process.

I have tried using sc.exe to manually create the service, and get the same error.

"Error 1053: The service did not respond to the start or control request in a timely fashion." seems to occur immediately after starting the service. The Event Logs do not have any events recorded.

Any help anyone could provide would be appreciated.

@mjsiers

This comment has been minimized.

Copy link

mjsiers commented Dec 19, 2018

I am also seeing this error using TopShelf 4.1.0 with .netcoreapp2.1 on win10-x64.
Any new ideas on how to get around this issue?

@mjsiers

This comment has been minimized.

Copy link

mjsiers commented Dec 19, 2018

Here is the Serilog output when starting on the command line.

[14:40:55 INF] Topshelf v4.1.0.172, .NET Framework v4.0.30319.42000
[14:40:57 ERR] The service failed to start.
System.InvalidOperationException: Cannot start service Agent on computer '.'. ---> System.ComponentModel.Win32Exception: The service did not respond to the start or control request in a timely fashion
--- End of inner exception stack trace ---
at System.ServiceProcess.ServiceController.Start(String[] args)
at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName, TimeSpan startTimeOut)
at Topshelf.Hosts.StartHost.Run()

@mjsiers

This comment has been minimized.

Copy link

mjsiers commented Dec 21, 2018

I was able to get this working and even upgraded my app to .netcoreapp2.2.

The issue was that I was doing too much work before the service started and this was causing the timeout error. My solution was to move all my initialization code into a background thread to reduce the service startup time.

@codermrrob

This comment has been minimized.

Copy link

codermrrob commented Dec 30, 2018

I get the same issue...

[15:05:40 DBG] Starting Emailer service
[15:05:42 ERR] The service failed to start.
System.InvalidOperationException: Cannot start service Emailer service on computer '.'. ---> System.ComponentModel.Win32Exception: The service did not respond to the start or control request in a timely fashion
   --- End of inner exception stack trace ---
   at System.ServiceProcess.ServiceController.Start(String[] args)
   at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName, TimeSpan startTimeOut)
   at Topshelf.Hosts.StartHost.Run()

.net core 2.1
Windows Server 2016/Win 10 Pro
TopShelf 4.1.0 (and 4.1.0.180)
Runtime win10-x64
Published as a Self-contained app.

As far as I can see everything should be OK. Code is basically the same as it usually is.

            HostFactory.New(tsc =>
            {

                int syslogPort = Convert.ToInt32(appSettings["SyslogPort"]);
                Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(appSettings)
                    .WriteTo.Console(theme: AnsiConsoleTheme.Code)
                    .WriteTo.Syslog("localhost", syslogPort, "Email Service", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message} {Properties} {Exception}")
                    .CreateLogger();

                tsc.UseAutofacContainer(_container);

                tsc.Service<EmailService>(svc =>
                {
                    svc.ConstructUsingAutofacContainer();
                    svc.WhenStarted((service, hostControl) => service.Start(hostControl));
                    svc.WhenStopped((service, hostControl) => service.Stop(hostControl));
                });

                tsc.SetStartTimeout(TimeSpan.FromSeconds(20));
                tsc.SetStopTimeout(TimeSpan.FromSeconds(20));

                tsc.EnableShutdown();
                tsc.SetServiceName(appSettings["ServiceName"]);
                tsc.SetDisplayName(appSettings["DisplayName"]);
                tsc.SetDescription(appSettings["Description"]);
                tsc.UseSerilog();
                tsc.RunAsNetworkService();
            });

The service itself is just starting up MassTransit, nothing unusual in it. And of course it runs fine in console mode. I don't think this is a time out issue so long as the SetStartTimeout works as I expect it to.

@lugerf

This comment has been minimized.

Copy link

lugerf commented Feb 24, 2019

I experienced the same issue where

  1. The installation failed by <TargetExecutable>.exe install and
  2. Manual registration by sc.exe of SysWOW64 worked, but resulted in error 1053 on service startup.

=> I could resolve it by changing my <RuntimeIdentifier> from win-x64 to win-x86. After the service installation (self-contained app on .net core 2.2, run on Windows10 64-bit) everything worked fine.

Could anyone explain to me, why win-x64 did not work?

@codermrrob

This comment has been minimized.

Copy link

codermrrob commented Feb 24, 2019

nice tip, but had a quick look at work around but no joy with it yet. No time to look at it deeper again until the end of next week. But will try again then and report back.

Perhaps in the meantime you could post your HostFactory config code and your PropertyGroup config from the project file, for comparison? Maybe I am doing something silly and missing it.

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <RuntimeIdentifiers>win10-x64</RuntimeIdentifiers>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <NoWarn>NU1605</NoWarn>
  </PropertyGroup>

I've been using NSSM to at least get the services installed but its not exactly an ideal solution :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.