Dispose method in web api 2 web service

早过忘川 提交于 2019-12-06 04:02:56

问题


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.


回答1:


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);
    }
}



回答2:


In Web Api 2, you can register a component for disposal when the request goes out of scope. The method is called "RegisterForDispose" and it's part of the Request. The component being disposed must implement IDisposable.

The best approach is to create your own extension method as 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 objects you want to dispose when request finalize...

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

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



来源:https://stackoverflow.com/questions/27895583/dispose-method-in-web-api-2-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!