views:

123

answers:

4

When you create a Windwows Service, you end up with a .exe file that you need to register, and you start it from the "Services" snap-in.

If you try to execute this .exe file, you get the message: "Cannot start service from the command line or debugger. A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command."

Is it somehow possible to set something in the service so that when run as a regular .exe, instead of displaying this message, it'll do something we can control in code? (Like run a Sub Main(), or something like that, that'd obviously be a different entry point than the one you get when you start it as a services)

Thanks!
Daniel

+1  A: 

You could write your application as a separate class library, and then create a stub exe to launch it?

Marineio
Yes, I thought of that, which implies at least 2 separate projects. What I want to find out is whether I can solve this using only one project.
Daniel Magliola
Separate EXEs is really the way to go here . . .
Wyatt Barnett
A: 

You could pass in an arg value.

something like app.exe -UI or app.exe -Service

Russ
+4  A: 

Well it is possible but I'm not sure it is a beautiful solution:

static void Main()
{
    bool your_condition = ReadRegistry or ReadConfigurationFile;
    if(your_condition)
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new YourService() 
        }
        ServiceBase.Run(ServicesToRun);
    }
    else
    {
        Application.Run(new YourForm())
    }
}

I didn't test it but I guess it would work.

Francis B.
Excellent, thank you!
Daniel Magliola
+2  A: 

We tend to build ours similar to Francis B. but use the conditional compiling:

#if DEBUG
    Application.Run(new YourForm())
#else
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
    { 
        new YourService() 
    }
    ServiceBase.Run(ServicesToRun);
#endif

That way it's easy to test and debug during development and then do a build deployment as a service.

I'm not sure from your question whether you want it actually released as a standalone exe, or just as a tool to aid development and testing.

Note, by the way, that you don't have to have a "application.run()" block in your debug version. If it's not showing a form, just any code that does an infinite loop while spawning your service's OnStart handler in a separate thread will be fine.

Clyde