我接管了软件的编码及其当前的编写方式,我不确定是否会调用UnitOfWorks中的Dispose()方法。我注意到我的SQL服务在一段时间(几天)之后就会停止,说所有连接都在用完。
我想知道以下代码是否正确完成,如果没有,我如何进行纠正以便调用dispose()方法。
UnitOfWorks.cs
public class UnitOfWorks
{
private KaprukaEntities context;
private GenericRepository<Transaction> transactionRepository;
private bool disposed;
public GenericRepository<Transaction> TransactionRepository
{
get
{
if (this.transactionRepository == null)
this.transactionRepository = new GenericRepository<Transaction>(this.context);
return this.transactionRepository;
}
}
public UnitOfWorks(KaprukaEntities entities)
{
this.context = entities;
}
public void Save()
{
this.context.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed && disposing)
this.context.Dispose();
this.disposed = true;
}
public interface IDisposable
{
void Dispose();
}
}
UnitOfWorks正在被服务类调用。
TransactionService.cs
public class TransactionService
{
private UnitOfWorks _unitOfWork;
private KaprukaEntities entities;
public TransactionService(UnitOfWorks unitOfWork)
{
this._unitOfWork = unitOfWork;
this.entities = new KaprukaEntities();
}
public bool Add(Transaction entity)
{
this._unitOfWork.TransactionRepository.Add(entity);
this._unitOfWork.Save();
var er = this.entities.GetValidationErrors();
return true;
}
public bool Update(Transaction entity)
{
this._unitOfWork.TransactionRepository.Update(entity);
this._unitOfWork.Save();
return true;
}
public bool Delete(Transaction entity)
{
this._unitOfWork.TransactionRepository.Delete(entity);
this._unitOfWork.Save();
return true;
}
public IEnumerable<Transaction> GetAll()
{
return this._unitOfWork.TransactionRepository.GetAll();
}
public IEnumerable<Transaction> GetAll(Expression<Func<Transaction, bool>> filter, Func<IQueryable<Transaction>, IOrderedQueryable<Transaction>> orderBy, string includeProperties)
{
return this._unitOfWork.TransactionRepository.Get(filter, orderBy, includeProperties);
}
}
调用它的方式如下:
有一个名为updateTransaction.aspx的文件,在其代码后面,代码调用服务:
updateTransaction.aspx
TransactionService TransServ = new TransactionService(new UnitOfWorks(new KaprukaEntities()));
var TransDetails = TransServ.GetAll(x => x.TransactionID == intTID, null, "").SingleOrDefault();
我看不到任何关闭或处置任何代码的代码。
答案 0 :(得分:0)
您的transactionservice构造函数创建了一个额外的db上下文,当一个已经在工作单元类中时:
this.entities = new KaprukaEntities();