在网页API 2 Web服务Dispose方法 [英] Dispose method in web api 2 web service

查看:260
本文介绍了在网页API 2 Web服务Dispose方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码与Web API 2 Web服务的MVC 5互联网应用。我是否需要在Web服务中的DbContext类Dispose方法?这是不存在的为默认值。

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.

推荐答案

其实, System.Web.Http.ApiController 已经实现了的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
}

所以,如果你的控制器拥有的DbContext,做到以下几点:

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

这篇关于在网页API 2 Web服务Dispose方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆