我正在创建一个处理器类并在工作者角色中运行。在处理器内部,我创建了存储库来对我的数据库进行 CRUD 操作。
我有 2 个存储库,产品和产品大小,dbcontext 在产品存储库中创建并传递给产品大小。
在我的本地机器上一切都运行良好,但是当我部署到 Azure 时,系统向我抛出了这个错误:
System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
处理器.cs
public class Processor : IDisposable
{
private readonly IProductRepository _productRepository;
public Processor()
: this(new ProductRepository())
{
}
public Processor(
IProductRepository productRepository
)
{
_productRepository = productRepository;
}
public void Run(){ _productRepository.someoperation;}
public void Dispose()
{
_productRepository.Dispose();
}
产品存储库.cs
public class ProductRepository : IProductRepository
{
private static readonly DbContext_context = new DbContext();
private readonly IProductSizeRepository _productSizeRepository;
public ProductRepository()
: this(
new ProductSizeRepository(_context))
{
}
public ProductRepository(
IProductSizeRepository productSizeRepository
)
{
_pictureRepository = pictureRepository;
}
public void Dispose()
{
_context.Dispose();
_productSizeRepository.Dispose();
}
在 workerrole.cs while 循环中使用 (var runner = new Processor()) { runner.Run(); }