何时在实体框架中调用Dispose?

时间:2010-05-01 13:35:58

标签: entity-framework spring.net

在我的应用程序中,我正在使用Spring.Net进行IoC。从ASP.Net文件调用服务对象以使用这些服务对象执行CRUD操作。例如,我有CustomerService在Customer表上执行所有CRUD操作。我使用实体框架并注入实体..我的问题是我在哪里调用dispose方法?

据我从API文档中了解,除非我调用Dispose(),否则无法保证它将被垃圾收集!那么我在哪里以及如何做到这一点?

示例服务类:

 public class CustomerService
{
    public ecommEntities entities = {get; set;}

    public bool AddCustomer(Customer customer)
    {
        try
        {
            entities.AddToCustomer(customer);
            entities.SaveChanges();
            return true;
        }
        catch (Exception e)
        {
            log.Error("Error occured during creation of new customer: " + e.Message + e.StackTrace);
            return false;
        }            
    }

    public bool UpdateCustomer(Customer customer)
    {
        entities.SaveChanges();
        return true;
    }

public bool DeleteCustomer(Customer customer)
.
.
.   

我只是在ASP分部类中创建一个CustomerService对象并调用必要的方法。

提前感谢最佳实践和想法。

此致

Abdel Raoof

2 个答案:

答案 0 :(得分:2)

我的应用程序中有HttpModule,它负责创建和处理上下文:

public class MyEntitiesHttpModule : IHttpModule
{
    public void Init(HttpApplication application)
    {
        application.BeginRequest += ApplicationBeginRequest;
        application.EndRequest += ApplicationEndRequest;
    }

    private void ApplicationEndRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Items[@"MyEntities"] != null)
            ((MyEntities)HttpContext.Current.Items[@"MyEntities"]).Dispose();
    }

    private static void ApplicationBeginRequest(Object source, EventArgs e)
    {
        //TextWriter logFile = File.CreateText(HttpContext.Current.Server.MapPath("~/sqllogfile.txt"));
        var context = new MyEntities();
        //context.Log = logFile;
        HttpContext.Current.Items[@"MyEntities"] = context;
    }
}

它在请求开始时创建它并在最后处置。上下文由Ninject从HttpContext.Current.Items获取并注入到我的服务对象中。我不知道它如何与Spring.Net一起使用以及你创建ObjectContext的方法是什么,但我希望这个答案会有所帮助。如果Sprint.Net支持每个请求的生命周期并且不需要任何模块,那么它也可以负责处理。在其他情况下,你可以像这里一样。

答案 1 :(得分:2)

@LukLed 通常正确(+1),HTTP请求是正确的范围。但是,我非常怀疑使用NInject或Spring.Net调用Dispose()需要显式代码,因为这些代码应该已经处理它们管理的实例。 HttpContext.Current可以将引用存储为任何内容。

然而,你(@Abdel)说:

是错误的
  

据我从API文档中了解,除非我调用Dispose(),否则无法保证它会被垃圾收集!

这是不对的。 Dispose()使集合更加优化,并提供非托管资源(例如,您的数据库连接)的确定性释放。但是,无论是否调用Dispose(),最终都会收集 的所有内容。

相关问题