ASP.NET Boilerplate中IDomainService单元测试报错:无法访问已释放对象
Fixing "Cannot access a disposed object" Error When Unit Testing IDomainService in ASP.NET Boilerplate (ABP)
Hey, I’ve run into this exact error while writing unit tests for IDomainService in ABP before—total headache, right? Let’s break down why this happens and how to fix it:
Common Causes
- Premature disposal of the DbContext instance: The error pops up when you try to use a DbContext that’s already been disposed. This usually happens if you’ve manually called
Dispose()on the context, or wrapped it in ausingblock which automatically disposes it after the block ends. - Mismanaged DI lifecycle: When using dependency injection, the DI container is supposed to handle creating and disposing instances like DbContext. If you’re bypassing the container and creating contexts manually, you’re taking on that responsibility—and it’s easy to mess up the disposal timing.
Fixes to Try
- Ditch manual context creation: Stop instantiating DbContext directly in your tests or domain services. Instead, let the ABP DI container inject it for you. For unit tests, make sure you’re using ABP’s test base classes (like
AbpIntegratedTestBase) which set up the DI container properly. - Remove any
usingblocks wrapping injected contexts: If you’ve got code likeusing(var context = _contextProvider.GetContext()), that’s a red flag—since the DI container already manages the context’s lifecycle, wrapping it inusingwill dispose it early, leading to this error later when something else tries to use it. - Check async operations: If your domain service uses async methods, make sure you’re not holding onto a reference to the context after the async operation completes. Await all async calls properly so the context doesn’t get disposed mid-operation.
内容的提问来源于stack exchange,提问作者Edward
相关产品推荐
相关产品推荐

