All notes
Servic

FAQ

Combo command line / windows service

SO: create a combo commandline/windows service app.

The best way to accomplish this from a design standpoint is to implement all your functionality in a library project and build separate wrapper projects around it to execute the way you want (ie a windows service, a command line program, an asp.net web service, a wcf service etc.).



// Class that represents the Service version of your app
public class serviceSample : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        // Run the service version here 
        //  NOTE: If you're task is long running as is with most 
        //  services you should be invoking it on Worker Thread 
        //  !!! don't take too long in this function !!!
        base.OnStart(args);
    }
    protected override void OnStop()
    {
        // stop service code goes here
        base.OnStop();
    }
}

// Then in Program.cs:

static class Program
{
    // The main entry point for the application.
    static void Main(string[] args)
    {
        ServiceBase[] ServicesToRun;

        // Instead of args check, you can check Environment.UserInteractive to see if we are in interactive mode or not. 
        if ((args.Length > 0) && (args[0] == "/console"))
        {
            // Run the console version here
        }
        else
        {
            ServicesToRun = new ServiceBase[] { new serviceSample () };
            ServiceBase.Run(ServicesToRun);
        }
    }
}