Wrapping a C# service in a console app to debug it

2019-01-23 01:39发布

I want to debug a service written in C# and the old fashioned way is just too long. I have to stop the service, start my application that uses the service in debug mode (Visual studio 2008), start the service, attach to the service process and then navigate in my Asp.Net application to trigger the service.

I basically have the service running in the background, waiting for a task. The web application will trigger a task to be picked up by the service.

What I would like to do is to have a console application that fires the service in an effort for me to debug. Is there any simple demo that anybody knows about?

10条回答
▲ chillily
2楼-- · 2019-01-23 02:32

Here is a blog post about running your windows service as a console app.

You could also just create a new Console Application that references the same logic as your service to test methods, or set up Unit Tests on your services' logic

查看更多
\"骚年 ilove
3楼-- · 2019-01-23 02:37

The approach I always take is to isolate out all of your application's logic into class libraries. This makes your service project really just a shell that hosts your class libraries as a service.

By doing this, you can easily unit test and debug your code, without having to deal with the headache of debugging a service by attaching to a process. I'd recommend unit testing of course, but if you're not doing that then adding a console application that calls the same entry point as your service is the way to go.

查看更多
Rolldiameter
4楼-- · 2019-01-23 02:37

I tend to have either a config setting or use a directive for debug builds:

 #if DEBUG
    Debugger.Break();
 #endif

or

if(Settings.DebugBreak)
            Debugger.Break();

I put that in the OnStart method of the service component. Then you are prompted automatically and attached to the process.

查看更多
The star\"
5楼-- · 2019-01-23 02:40

To avoid using global defines I generally test at run-time whether I'm a service or regular application through the Environment.UserInteractive property.

    [MTAThread()]
    private static void Main()
    {
        if (!Environment.UserInteractive)
        {
            ServiceBase[] aServicesToRun;

            // More than one NT 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 ServiceMain, New MySecondUserService}
            //
            aServicesToRun = new ServiceBase[] {new ServiceMain()};

            Run(aServicesToRun);
        }
        else
        {
            var oService = new ServiceMain();
            oService.OnStart(null);
        }
   }
查看更多
登录 后发表回答