开发者

One executable that starts as console or win32 service based on command line parameter in .NET?

开发者 https://www.devze.com 2023-01-22 08:57 出处:网络
Is it possible to write executable application in .net that can be registered as Win32 Service and operate as service but for debu开发者_运维百科g purposes can be launched as console application with

Is it possible to write executable application in .net that can be registered as Win32 Service and operate as service but for debu开发者_运维百科g purposes can be launched as console application with console output (as performance counters, text log files are not very useful for monitoring)

Or shall I put application logic (Application class) in a separate assembly and write two completely different executable wrappers (win32 service and console) that reference this library with Application class?

Console

main()
{
  Application.Start();
  Console.Readkey();
  Application.Stop(); 
}

Win32 Service

OnStart()
{
  Application.Start();
}

OnStop()
{
  Application.Stop();
}


Yes I have done this before. I created a windoes service project, changed the type to Console Application on project properties (from windows application) and added a condition based on command line parameter:

/// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main(string[] args)
    {

        // setup DI 
        BootStrapper.Setup();

        if (!Environment.UserInteractive)
        {
            ServiceManager serviceManager = new ServiceManager();
            serviceManager.Start();
        }
        else if(args.Length==1 && args[0]==HarnessGuid)
        {
            RunInHarnessMode();
        }
        else
        {
            ServiceBase[] servicesToRun = new ServiceBase[] { new ServiceManager() };
            ServiceBase.Run(servicesToRun);
        }       
    }

UserInteractive can also do the trick.


In your Main() method detect if you want to run as a console or service. If running as a console, just call OnStart() directly. If running a as a service, call Run().

0

精彩评论

暂无评论...
验证码 换一张
取 消