Quartz.Net作业中使用的DBContext的Ninject范围 [英] Ninject scoping for DBContext used in Quartz.Net job

查看:268
本文介绍了Quartz.Net作业中使用的DBContext的Ninject范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Quartz.Net作业实现的执行过程中,通过Ninject依赖关系解析器实例化的DbContext实现的最佳范围是什么?如果我使用了线程作用域,并且使用Quartz线程池中的同一线程多次执行作业,是否可以提供DbContext的同一实例?

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?

我想要一个作用域,这意味着每次作业被解雇时,我都会获得一个(只有一个)DbContext新实例.

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

推荐答案

是的,我建议您不要使用InThreadScope.使用线程池线程时,会发生泄漏.

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

此外,ninject没有像"QuartzScope"那样内置任何内容,因此您必须创建自己的解决方案.让我们从实例化作业开始.这由此stackoverflow答案覆盖,更广泛地由此nuget包的源代码.

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.

现在,一种可行的解决方案是扩展JobFactory来管理DbContext的创建,并将其注入到作业及其所有依赖项中(作为继承的ConstructorArgument参数).但是,这样做有两个缺点:始终创建DBContext(无论作业是否需要),并且需要跟踪DBContext实例,以便可以在IJobFactory.ReturnJob(IJob)方法中对它们进行.Dispose()(p.ex (由Dictionary<IJob, DBContext等).

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).

更简单的方法是使用.InCallScope(包含在 Ninject.Extensions.NamedScope )用于DbContext绑定.这将为每个kernel.Get<FooJob>()创建一个DbContext实例.

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>().

如果DbContext需要具有不同的作用域-根据使用的范围,请参见p.Ex.在Job内和ASP.NET MVC内,您可能需要查看

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?

这篇关于Quartz.Net作业中使用的DBContext的Ninject范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆