This is part of a series on creating and installing Windows services.
- How to Create a Windows Service
- How to Install a Windows Service
- How to Run a Windows Service from Visual Studio
So far, we have learned how to create a basic shell for a Windows service and how to install it using both sc
and InstallUtil
. Currently, the code for our simple demo service looks like this:
As we saw in our first episode, if we simply run this application from Visual Studio (perhaps via the F5 key), we are met with this error message informing us that we cannot run the service from the command line or debugger:
If we want to be able to efficiently develop our service from Visual Studio, it sure would be nice if we could actually run (and/or debug) it from Visual Studio. To begin, we need to abstract MyService
away from the fact that is running via an implementation of ServiceBase
. To do so, we will create a new reusable implementation of ServiceBase
, called BasicService
:
Note that BasicService
overrides the two critical methods on ServiceBase
, OnStart and OnStop, which are called when the service is commanded to start and stop by the service control manager. BasicService
delegates those calls to a collaborating interface, IService
. In order to convert our existing service to use this new infrastructure, we must change MyService
to implement IService
, and slightly modify our Main
method:
Now that the "complex business logic" of our application (yes, I know it still doesn't do anything) is abstracted away from the fact that it will run via a service, we are free to run it another way. Utilizing Environment.UserInteractive, we can modify the main method to turn our application into a hybrid console/service application:
Running the application no longer throws up an error!
Since I did promise that we would have the service actually do something this time, let's build out MyService
a bit:
The service will simply write a message to the console every second until we stop it. And because of our changes today, we can easily verify that by hitting F5:
Note that it is also possible to run the service by calling the executable from an interactive command line or by double-clicking it in Windows Explorer. These approaches also trigger the "run as a console app" branch in our main method. With just a little bit of additional code, we have made it much easier to develop and debug our service.
Run a Windows Service from Visual Studio is a post from: DevOps On Windows - Be awesome at Windows DevOps or Windows Sysadmin
The post Run a Windows Service from Visual Studio appeared first on DevOps On Windows.
No comments:
Post a Comment