Recycle method in web api 2 web service

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 the web service? This is not the default.

+3


source to share


2 answers


Actually, it 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 contains 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);
    }
}

      

+12


source


In Web Api 2, you can register a component to be removed when a request goes out of scope. This method is called "RegisterForDispose" and is part of the request. The component being installed must implement IDisposable.

The best approach is to create your own extension method as shown below ...

       public static T RegisterForDispose<T>(this T toDispose, HttpRequestMessage request) where T : IDisposable
   {
       request.RegisterForDispose(toDispose); //register object for disposal when request is complete
      return toDispose; //return the object
   }

      



Now (in your api controller) you can register the objects you want to delete when the request is complete ...

    var myContext = new myDbContext().RegisterForDispose(Request);

      

Links ... https://www.strathweb.com/2015/08/disposing-resources-at-the-end-of-web-api-request/

0


source







All Articles