0
votes

I have an Entity Framework context being injected into a background job (handled with Hangfire.io). Hangfire spawns threads for each background worker... But runs multiple jobs on the same worker. So my EF context may be kept around for a long time.

I'd like to remove the Ninject instance for a Job's thread at the end of it's execution. Thus causing it to create a new instance for the next resolution of that type in the same thread.

How do I go about removing an instance from an InThreadScope in Ninject?

1
Why do you have to use InThreadScope, why not just InTransientScope, for the EF context? - Roy Dictus
The background task being used comprises a number of separate steps that don't all pass the context from one to another. However they do pass entities (to avoid lots of DB calls). - Ben Ford

1 Answers

0
votes

Hangfire can notify you on Job performing (before) and performed (after) through a JobFilterAttribute that implements IServerFilter, basically something like:

public class MyJobAttribute : JobFilterAttribute, IServerFilter
{

    public void OnPerformed(PerformedContext performedContext)
    {
        //here you'll be called on the same thread of the job after it has been executed

    }

    public void OnPerforming(PerformingContext performingContext)
    {
        //here you'll be called on the same thread of the job that will be executed
    }

}

Just apply that MyJobAttribute on the class/methods of your job