Thursday, April 22, 2021

Dependency injection for background task

Recently I faced a requirement where from a method I needed to call an independent background task.  Below is a snippet

public Task Handler()
{
    ... do something
    ... BackgroundTask()
    ... do something
}

The challenge that was encountered is that the background task was required to make use of objects  which were instantiated within the constructor of the class via dependency injection.

public class MyService
{
    private readonly IMediator mediator;
    public MyService(IMediator mediator)
    {
        this.mediator = mediator;
    }
}

The background task was required to make use of the mediator object.  However upon running this code, I started experiencing Cannot access a disposed object.

To overcome this problem what was required is to created a scoped object within the background job.  Hence we made use of the IServiceScopeFactory which would help in instantiating an object for the required service within the scope of the background task.

public class MyService
{
    private readonly IMediator mediator;
    private readonly IServiceScopeFactory scopeFactory;
    public MyService(IMediator mediator, IServiceScopeFactory scopeFactory)
    {
        this.mediator = mediator;
        this.scopeFactory = scopeFactory;
    }
    public void BackgroundTask()
    {
        using var scope = scopeFactory.CreateScope();
        var scopedMediator = scope.ServiceProvider.GetRequiredService<IMediator>();
        ... etc
    }
}

No comments: