3

I'm writing a Windows service that will self-host an OWIN WebApi web service. To start the web service, the location is pretty obvious; in the OnStart method of the ServiceBase-extending class:

private IDisposable _webApiDataConnectionHost;

protected override void OnStart(string[] args) {
    _webApiDataConnectionHost = WebApp.Start<OwinWebStartup>("...");
}

However, I'm not sure where to dispose of the web app. In this example project, they dispose of it in the OnStop method:

protected override void OnStop()
{
    if(_server != null)
    {
        _server.Dispose();
    }
    base.OnStop();
}

However given that this is an IDisposable, wouldn't it be correct to dispose of it in the service's override of the Dispose method? Something like the following:

protected override void Dispose(bool disposing) {
    if (disposing) {
        if (components != null) { components.Dispose(); }

        // Dispose of our web app if it exists...
        if (_webApiDataConnectionHost != null) {
            _webApiDataConnectionHost.Dispose();
        }
    }

    base.Dispose(disposing);
}

Which is the proper place to dispose of the web app?

Jez
  • 27,951
  • 32
  • 136
  • 233

2 Answers2

1

The way I typically setup any service is to implement the IDisposable interface and call the Dispose method from the OnStop. My OnStop is normally the same as my OnPause with the additional call to Dispose. You can see the recommendation from msdn here.

Kent Cooper
  • 4,319
  • 3
  • 19
  • 23
0
  • Being IDisposable guarantees garbage collection, sooner or later.
    • If you will not call Dispose(), the collection is likely to happen later non-deterministically.
  • Since it is a service, you know when you want the service to stop, therefore it makes all the sense to call Dispose() yourself, rightly so in OnStop().
  • Also, you will be running only a single instance of it - so use Singleton design pattern. Implement the thread safe pattern if multiple threads will be accessing the singleton instance.

If I'm getting it correctly, the code you have written in the service's override of Dispose() is simply ensuring that when the instance will be garbage collected, all resources will be released. With that method you are ensuring that dispose will happen correctly, whenever it happens. You still need to call this overriding method in OnStop().


* Do I need to dispose a web service reference in ASP.NET?

* Remarks on Disposing ServiceBase - Also linked in Kent Cooper's answer.

Community
  • 1
  • 1
displayName
  • 13,888
  • 8
  • 60
  • 75