【发布时间】:2019-12-12 12:22:10
【问题描述】:
我有一个关于管理 LINQ to SQL 数据库上下文的生命周期的问题。目前,我正在使用工厂在需要时实例化一个新的数据库上下文。在某些情况下这很好,但在其他情况下则不然。例如,当一个操作跨越多个方法时,在每个方法中我都调用工厂来生成一个新实例,而我确实需要在操作的生命周期内在方法之间共享上下文。理论上,操作需要是原子的。所以,我的问题是想知道在工厂中有多个工厂方法来在需要的时候获取所需的上下文是否是一个好的设计?
我在下面提供了一个示例实现。
// 接口
public interface IEntityContextFactory : ISingletonService
{
IDbContext CreateContext();
IDbContext GetContext();
}
//工厂类
public class EntityContextFactory : IEntityContextFactory
{
private IDbContext _context;
public IDbContext CreateContext()
{
var defaultConnectionString = ConfigurationManager.ConnectionStrings["connection_name"].ConnectionString;
var database = new DataContext(defaultConnectionString);
// this is a wrapper around the linq to sql context
return new DbContext(database);
}
public IDbContext GetContext()
{
// TODO: make threadsafe
if(_context == null)
{
_context = CreateContext();
return _context;
}
return _context;
}
}
【问题讨论】:
标签: c# linq-to-sql datacontext