Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject scoping for DBContext used in Quartz.Net job

What's the best scoping to use for a DbContext implementation that gets instantiated via Ninject dependency resolver during execution of a Quartz.Net job implementation? If I used thread scope, will the same instance of DbContext get served if the same thread in Quartz's thread pool is used to execute the job multiple times?

I would like a scope that means I get one (and only one) new instance of the DbContext each time the job is fired.

like image 843
Simon Green Avatar asked Aug 16 '14 12:08

Simon Green


1 Answers

Yes, i would advise against using InThreadScope. When a thread-pool thread is used, there will be leakage.

Furthermore, there's nothing built-in into ninject like a "QuartzScope", so you'll have to create your own solution. let's start with the instantiation of the job. That's covered by this stackoverflow answer and, more extensively, by the source code of this nuget package.

Now one possible solution is to extend the JobFactory to manage the creation of the DbContext and inject it into the job and all its dependencies (as an inherited ConstructorArgument parameter). However, that has two drawbacks: Always creates a DBContext (whether the job needs it or not), and you need to track DBContext instances so you can .Dispose() of them in the IJobFactory.ReturnJob(IJob) method (p.ex. by a Dictionary<IJob, DBContext or the likes).

The much easier way is to use .InCallScope (included in Ninject.Extensions.NamedScope) for the DbContext binding. This will create one DbContext instance per kernel.Get<FooJob>().

If you need to have different scopes for your DbContext - depending on where you use them, p.Ex. inside a Job and inside your ASP.NET MVC stuff, you might want to look at Ninject Conditional Self bind to change scope (For Task-scheduler) not working properly?

like image 55
BatteryBackupUnit Avatar answered Nov 03 '22 00:11

BatteryBackupUnit