C# run Windows Service project as regular Windows application

T

Trevor

In C++ you can allow your Windows program to act as a Windows Service by
implementing some functions required by the Service Control Manager. This
same application could be written in such a way that the application could
run as a regular Windows Application or as a Windows Service. How can I do
this in C#? I am using Visual Studio 2003.
 
N

Nicholas Paldino [.NET/C# MVP]

Trevor,

The models for an application and a service are different from each
other. For example, an app usually requires some sort of user interaction,
whereas services are interacted with in a different manner. Also,
applications usually have UI, whereas a service will not.

What you should do is separate your business logic (not involving UI)
into another assembly, then have the Windows Application and the Service
project reference it.

Hope this helps.
 
T

Trevor

Nicholas Paldino said:
Trevor,

The models for an application and a service are different from each
other. For example, an app usually requires some sort of user
interaction, whereas services are interacted with in a different manner.
Also, applications usually have UI, whereas a service will not.

What you should do is separate your business logic (not involving UI)
into another assembly, then have the Windows Application and the Service
project reference it.

I was afraid it would come down to this. Thanks for taking the time to
respond.
 
J

John Duval

Hi Trevor,
While I agree with Nicholas Paldino's comments, I have done what you
are asking for testing purposes. If the project is based on the .NET
Service template, you can just call the service's OnStart() method from
Main(), something like this:

static void Main()
{
bool runInteractive = true;
if (runInteractive)
{
MyServiceClass svc = new MyServiceClass();
svc.StartInteractive();
return;
}
System.ServiceProcess.ServiceBase[] ServicesToRun;

// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new
Service1(), new MySecondUserService()};
//

ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
MyServiceClass () };

System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

and in MyServiceClass, just add this function:

public void StartInteractive()
{
OnStart(null);
}

Hope this helps,
John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top