Daniel Magliola
Daniel Magliola

Reputation: 32392

.Net Service and Windows App at the same time?

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

Upvotes: 0

Views: 211

Answers (4)

Clyde
Clyde

Reputation: 8145

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.

Upvotes: 2

Francis B.
Francis B.

Reputation: 7208

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.

Upvotes: 4

Russ
Russ

Reputation: 12530

You could pass in an arg value.

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

Upvotes: 0

Marineio
Marineio

Reputation: 415

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

Upvotes: 1

Related Questions