全局DataContex声明

本文关键字:声明 DataContex 全局 | 更新日期: 2023-09-27 18:15:14

在我的服务接口中,我在每个方法中声明了DataClasses1DataContext data = new DataClasses1DataContext();。我可以声明它一次,并使所有方法都可以访问吗?

全局DataContex声明

您可以将其作为实例变量存储在您的类中:

public class SomeClass : IDisposable
{
    private readonly DataClasses1DataContext _context;
    public SomeClass()
    {
        _context = new DataClasses1DataContext();
    }
    public void Dispose();
    {
        _context.Dispose();
    }
    public void Method1();
    {
        // You can use the _context here
    }
    public void Method2();
    {
        // You can use the _context here
    }
    ... 
}

现在您可以在类的所有方法中使用context字段。但是请记住,DbContext应该是短暂存在的。您应该避免将它存储在一些静态字段中。最好的方法是每个HTTP请求都有一个DbContext。

当然。通过使用一个控制公开数据上下文生命周期的静态属性,您可以声明它一次,但仍然在特定时间段内创建它。特别是,为每个http请求创建一个上下文(如果您在IIS中托管服务)是一个好主意,这比到处创建实例要好得多。

我几年前就写过了。

http://www.wiktorzychla.com/2010/12/container-based-pseudosingletons-in.html

更高级的方法是使用IoC容器,并在IoC基础设施创建服务时自动创建和注入数据上下文。看看我的另一个教程

http://www.wiktorzychla.com/2014/02/lifetime-management-of-wcf-services.html