none
Windows Service doesn't execute OnStart() RRS feed

  • Question

  •      

    I have a windows service that is having trouble executing the Onstart() method after installing it and running it from the service menu.I'm logging everything that is happening at every step of the execution to see where the problem is. But there is no error, it logs and runs fine in the main method , up until the service is actually called to run and then it just does nothing.

    It's interesting to note that it doesn't have ANY problem running in debug.

    My program class(starting point) from which the service is called : 

    using System;
    using System.Configuration;
    using SimpleInjector;
    using System.ServiceProcess;
    using Microsoft.Extensions.Logging;
    using SimpleInjector.Lifestyles;
    using SmsHandler.Domain;
    using SmsHandler.Interfaces;
    using SmsHandler.Interfaces.Configuration;
    using SmsHandler.SimpleInjector;
    
    namespace SmsHandler.Sender
    {
        public class Program
        {
            private static Container _container;
            private static ILogger<Program> _logger;
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            private static void Main()
            {
                _container = SimpleInjectorContainer.Build(registerConfig: true, useThreadScopedLifestyle: true);
                SimpleInjectorContainer.LoggAndVerify(_container);
    
                using (ThreadScopedLifestyle.BeginScope(_container))
                {
                    try
                    {
                        _logger = _container.GetInstance<ILogger<Program>>();
                        _logger.LogInformation("Test - Works");
                        VerifyConfiguration();
                    }
                    catch (Exception ex)
                    {
                        var logger = _container.GetInstance<ILogger<Program>>();
                        logger.LogError(ex, "Configuration is not valid");
                        throw;
                    }
    
                    if (Environment.UserInteractive)
                    {
                        RunDebug();
                    }
                    else
                    {
                        System.Diagnostics.Debugger.Launch();
                        _logger.LogInformation("It's Here 49");
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[]
                        {
                            _container.GetInstance<SenderService>()
                        };
                        _logger.LogInformation(_container.GetInstance<SenderService>().GetType().ToString());
                        //_logger.LogInformation("It's Here 56");
                        ServiceBase.Run(ServicesToRun);
                        _logger.LogInformation("It's Here 58");
                    }
                }
            }
    
            private static void RunDebug()
            {
                var senderService = _container.GetInstance<SenderService>();
                senderService.TestStart();
                Console.WriteLine("Sender Started Debug");
                Console.ReadLine();
                senderService.TestStop();
            }
            private static void VerifyConfiguration()
            {
                var configValidator = _container.GetInstance<IConfigurationValidator>();
                configValidator.VerifyOperatorPrefixNumbers();
                configValidator.VerifyConfiguration();
                configValidator.VerifyOperators();
                //configValidator.VerifyOperatorMaxSmsCheckCount();
    
                // TODO: Check Operator attributes except Unknown
            }
        }
    
    }
    
       




    My actual service : 

    using System;
    using System.ServiceProcess;
    using System.Threading;
    using Microsoft.Extensions.Logging;
    using SimpleInjector;
    using SimpleInjector.Lifestyles;
    using SmsHandler.Interfaces;
    using SmsHandler.Interfaces.Configuration;
    
    namespace SmsHandler.Sender
    {
        public partial class SenderService : ServiceBase
        {
            private readonly Container container;
            private readonly ILogger<SenderService> logger;
            private readonly ISmsHandlerConfig config;
            private readonly IConfigurationValidator configValidator;
    
            public SenderService(
                Container container,
                ILogger<SenderService> logger,
                ISmsHandlerConfig config,
                IConfigurationValidator configValidator)
            {
                this.InitializeComponent();
                this.container = container;
                this.logger = logger;
                this.config = config;
                this.configValidator = configValidator;
            }
    
            public void TestStart()
            {
                Console.WriteLine($"Starting {ServiceName} service");
                this.OnStart();
            }
    
            public void TestStop()
            {
                Console.WriteLine($"Stopping {ServiceName} service");
                this.OnStop();
            }
    
            protected void OnStart()
            {
                try
                {
                    this.logger.LogInformation($"{this.ServiceName} starting");
                    SmsHandlerAction();
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, $"Error starting service {this.ServiceName}");
                    throw;
                }
            }
    
            protected override void OnStop()
            {
                try
                {
                    this.Dispose();
                    this.logger.LogInformation($"{this.ServiceName} stopped");
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, $"Error stopping service {this.ServiceName}");
                }
            }
    
            private void SmsHandlerAction()
            {
                while (true)
                {
                    this.logger.LogInformation($"{this.ServiceName} started");
                    using (ThreadScopedLifestyle.BeginScope(this.container))
                    {
                        var smsSenderService = this.container.GetInstance<ISmsSenderService>();
                        var sendResult = smsSenderService.SendSms(this.container);
    
                        // Wait if there are not messages for sending
                        if (!sendResult && this.config.IdleTimeMiliseconds != 0)
                        {
                            Thread.Sleep(this.config.IdleTimeMiliseconds);
                        }
                    }
                }
            }
        }
    }


    this is what is logged:

    > 2019-02-12 18:02:18.7972 INFO Test - Works

    > 2019-02-12 18:02:20.6370 INFO It's Here 49

    > 2019-02-12 18:02:20.6410 INFO It's Here 56

    and after I stop the service :

    > 2019-02-12 18:02:35.7375 INFO SenderService stopped

    > 2019-02-12 18:02:35.7375 INFO It's Here 58

    It missing the `this.logger.LogInformation($"{this.ServiceName} starting");` part.

    It doesn't log the line in the onstart method , because it never actually executes, I checked if the service was running, but just failed to log and that is not the case.    

    My IDE is VS 2017, OS is Win 7, DI library is SimpleInjector 4.0.12.

    I know about a similar question asked on here(cant link it currently, Ill post it at the bottom as text) but I don't see how it solves my problem.

    I'm pretty lost so any guidance will be of help.

    The other question :

    social.msdn.microsoft.com/Forums/vstudio/en-US/b8c8638c-49bf-4f77-a4eb-ad1af0c8d0f5/windows-service-doesnt-execute-onstart?forum=csharpgeneral

    Wednesday, February 13, 2019 7:56 AM

All replies

  • Hi Nikolay 123,

    Thank you for posting here.

    For your question, you want to solve the problem that Windows Service doesn't execute OnStart().

    You could set the breakpoint to see if OnStart method is executed. If so, you could check if the statement is right.

    If not, please provide more details to reproduce your problem.

    We are waiting for your update.

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, February 14, 2019 8:14 AM
    Moderator
  • The log messages you posted as appearing don't appear in the code you posted anywhere. Where do these come from? Can you post the code that actually calls your service because a service is just a component of the service process. It is the responsibility of the service process to start the service. 

    Also, services have service installers. Did you install the service into the SCM? If you didn't then it cannot run as a service. When you configure the installer for the service it'll automatically configure an event source to log start and stop of the service to the System log. Provided your service name (aka the ServiceBase.ServiceName property) matches the ServiceInstaller.ServiceName property then start/stop requests are logged to the event log. You can check there.

    You should ideally be logging your warnings/errors to the provided EventLog property as well. If you don't then sys admins won't have access to this useful information when your service is not behaving correctly. It's fine to have custom logging as well but services should log critical information the event log.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, February 15, 2019 2:53 PM
    Moderator
  • Hi

    Is your problem solved? If the issue still exists, please feel free let me know.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, February 19, 2019 8:17 AM
    Moderator