Ninject InRequestScope退回到InThreadScope

编程入门 行业动态 更新时间:2024-10-08 12:37:08
本文介绍了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.

因此,请转到版本的源代码,查看InRequestScope和InThreadScope的含义,并创建一个汞合金(然后可以将其作为扩展方法与其他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

本文发布于:2023-11-28 04:12:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640906.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ninject   InRequestScope   InThreadScope

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!