Ninject InRequestScope退回到InThreadScope [英] Ninject InRequestScope fallback to InThreadScope

查看:77
本文介绍了Ninject InRequestScope退回到InThreadScope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC3项目中,我将内核设置为在 Ninject Entityframework 上下文,这很完美.但是我有一个后台运行程序来执行一些工作流管理.

In my MVC3 project I've setup my kernel to Ninject the Entityframework context on a InRequestScope basis, this works perfect. But I have a background runner that does some workflow management.

它每5分钟启动一个新线程,然后我将依赖项 Ninject 插入该线程,如果将范围更改为InThreadScope,则Dispose方法将被触发,但是如果将其更改回InRequestScope Dispose方法不会触发.

It fires up a new thread each 5 minutes and I Ninject my dependencies into this thread, If I change the scope to InThreadScope the Dispose method is fired, but If I change it back to InRequestScope the Dispose method won't fire.

如果InRequestScope不可用,是否有回退到InThreadScope的方法?

Is there a way of fallbacking to InThreadScope if InRequestScope isn't available?

更新:刚刚对此问题表示赞同,为什么不使用其他信息进行更新.我认为Ninjects处理生活时间的方式有点过时了.其他IoC的子容器是在整个子容器中都存在的暂态注册对象,并在子容器存在时进行处置.这是一种将Web API与自定义工作程序相结合的简便方法,就像上面的场景一样.

Update: Just got an upvote for this question and why not update it with some additional info. I think that Ninjects way of handling life time is a bit outdated. Other IoC's have child containers were Transient registered objects live during the whole child container and are disposed when the child containers are. This is a much easier way of combining for example Web API with a custom worker like above scenario.

推荐答案

有一个InScope方法,您可以使用该方法指定自定义范围规则.

There's an InScope method, with which you can specify a custom scoping rule.

InRequestScope的实现当前正在从2.2-2.4发生变化.

The implementation of InRequestScope is currently undergoing change from 2.2-2.4.

因此,请转到版本的源代码,查看InRequestScopeInThreadScope的含义,并创建一个汞合金(然后可以将其作为扩展方法与其他InXXXScope方法一起插入.

So go to the source of your version, look at the impl of InRequestScope and InThreadScope and create an amalgam (which you can then slot in as an extension method alongside the other InXXXScope methods.

看起来(在将其提取到扩展方法之前)如下:

It'll look (before you extract it into an extension method) something like:

Bind<X>.To<T>().InScope( ctx => ScopeContext.Request(ctx) ?? ScopeContext.Thread(ctx))

另一种方法是创建两个Bind,并具有适当的约束,例如WhenInjectedInto<T>,以基于上下文绑定.

The other way is to create two Bindings, with an appropriate constraint such as WhenInjectedInto<T> to customize the scoping based on the contextual binding.

这篇关于Ninject InRequestScope退回到InThreadScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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