Dispose method in web api 2 web service

user3736648 picture user3736648 · Jan 12, 2015 · Viewed 11.8k times · Source

I am coding an MVC 5 internet application with a web api 2 web service. Do I need a dispose method for the DbContext class in a web service? It is not there as default.

Answer

John Saunders picture John Saunders · Jan 12, 2015

Actually, System.Web.Http.ApiController already implements IDisposable:

// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the  project root for license information.
// ...
public abstract class ApiController : IHttpController, IDisposable
{
// ...
    #region IDisposable

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
    }

    #endregion IDisposable
}

So, if your controller holds a DbContext, do the following:

public class ValuesController : ApiController
{
    private Model1Container _model1 = new Model1Container();

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