views:

16

answers:

2

Is it possible to write executable application in .net that can be registered as Win32 Service and operate as service but for debug 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();
}
+2  A: 

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.

Aliostad
+1  A: 

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().

Sam