public class CommonService
{
private readonly DataContext _context;
public CommonRepository()
{
_context = new DataContext();
}
public CommonRepository(DataContext context)
{
_context = context;
}
public List GetAll()
{
var query = from m in _context.MyModel
select m;
return m.ToList();
}
}
要么
public class CommonService
{
public List GetAll()
{
using (DataContext context = new DataContext())
{
var query = from m in context.MyModel
select m;
return m.ToList();
}
}
}
或者你有更多的模式,请建议我 .
2 回答
这里有一个主要区别:第一个代码示例在服务的生命周期中保留单个DataContext,而第二个示例为每个操作旋转一个新的 . 第二个例子通常是正确的,因为使用更改跟踪,DataContext可以变得非常大,如果其他东西调用
SubmitChanges()
,你可以意外地提交你不想提交的东西 .见Multiple/single instance of Linq to SQL DataContext
您可以使用这两种模式,但始终确保上下文的使用寿命较短 . 第一个选项允许您在
CommonService
中创建需要上下文的方法,但无需在每个方法中创建一个方法 . 所以它可以防止重复的代码 . 此外,它允许IoC容器通过构造函数注入将上下文注入CommonService
.如果你选择第一个选项(我倾向于这样做),你可以考虑使用
CommonService
实现IDisposable
,给它一个Dispose
方法来处理上下文 . 这也将鼓励您在using
构造中使用CommonService
,从而限制其寿命 .