You can have both projects in the same solution. There are many options to interact with your service. The best choice depends on the actions you want the UI application to perform with the service.
My choice would be to use a WCF service hosted within your windows service application. There are many examples out there for self-hosted WCF services (one is here, though I didn't read it all).
Please note #1: To add the service reference to the client, you need to start the host outside Visual Studio in case you have both projects in the same solution, as the "Add service reference" menu item will not be available when running something in Visual Studio.
Please note #2: It might be a good idea to create your windows service to be able to run as a GUI application when Environment.UserInteractive == true
. To do so, I tend to modify the Main
method to either start the service, or to start a GUI using the code found when creating a Windows Forms application (Application.Run(new SomeForm())
, etc.). That makes debugging a lot easier.
To avoid confusion: I'm not talking about creating a user-interactive service! I'm talking about making your service application so that it can run both as a service and as an application for debugging purposes. Like this, for example:
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DebugForm(new MyService()));
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
}
}
Add new methods DoStart()
and DoStop()
to your service class that just call OnStart
and OnStop
to simulate the service being started. Call DoStart
from the form's OnLoad
handler and DoStop
from the form's OnClose
handler.
Of course you need to add System.Windows.Forms
and System.Drawing
references to your project to allow forms to be used.
That way you can just run your service application from Visual Studio without the "A service can not be run as an application" message.
You still need to create a UI application to interact with the service! The above only helps for debugging the service and is something I've come to love, because it makes development much easier!