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.
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 inheritedConstructorArgument
parameter). However, that has two drawbacks: Always creates aDBContext
(whether the job needs it or not), and you need to trackDBContext
instances so you can.Dispose()
of them in theIJobFactory.ReturnJob(IJob)
method (p.ex. by aDictionary<IJob, DBContext
or the likes).The much easier way is to use
.InCallScope
(included in Ninject.Extensions.NamedScope) for theDbContext
binding. This will create oneDbContext
instance perkernel.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?