Richard Forrest
Richard Forrest

Reputation: 3616

ObjectDisposedException when trying to use the DBContext inside an IDistributedEventHandler

I have an ABP app where we are using the IDistributedEventHandle. In these handlers I want to use the custom repository that we have in the application. This repository inherits from the Volo EfCoreRepository. However when the event handlers are executed I get ObjectDisposedException on the primary DbContext. I'm assuming this is because its now being used outside of asp.net primary scope.

 public class EventHander : IDistributedEventHandler<ClientCreatedEto>,
    ITransientDependency
{
    private readonly ICustomRepository _repository;


    public EventHander (ICustomRepository repo)
    {
        _repository= repo;
    }

    public async Task HandleEventAsync(ClientCreatedEto eventData)
    {
       //error here
    }
}

I have also tried taking a dependency on IServiceProvider declaring a new scope and resolving the repository that way but I get the same exception. How should the primary DBContext for the application be resolved in eventhandlers?

Upvotes: 1

Views: 266

Answers (1)

maliming
maliming

Reputation: 185

You can try to use IUnitOfWorkManager in the HandleEventAsync method to create a unit of work, and use repositoryin the unit of work.

using (var uow = _unitOfWorkManager.Begin())
{
    // your _repository method code.
    await uow.CompleteAsync();
}

Or use [UnitOfWork] attribute.

[UnitOfWork]
public virtual async Task HandleEventAsync(ClientCreatedEto eventData)
{
   // your _repository method code.
}

Upvotes: 1

Related Questions