Ninject范围的问题与任务/线程 [英] Ninject Scope issue with Tasks/Threads
问题描述
我有一个使用Ninject,实体框架和工作模式的单位与服务层的MVC3项目。
我AsyncService类有启动一个后台任务,作为一个例子,将用户添加到用户信息库的功能。
我现在的问题是,之前,我认为的DbContext已经被布置在错误的任务只运行正确了几秒钟。
我的数据库上下文,它是注射Ninject的InRequestScope()似乎是越来越处置,如InRequestScope()它关系到HttpContext的。
我读过有关InThreadScope(),但我不知道如何正确实现它在我的MVC项目。
我的问题是:什么是我的任务使用Ninject的正确方法
? 公共类AsyncService
{
私人CancellationTokenSource cancellationTokenSource;
私人IUnitOfWork _uow;
公共AsyncService(IUnitOfWork UOW)
{
_uow = UOW;
}
公共无效AsyncStartActivity(活动活动)
{
...略...
this.cancellationTokenSource =新CancellationTokenSource();
VAR的CancellationToken = this.cancellationTokenSource.Token;
VAR任务= Task.Factory.StartNew(()=>
{
的foreach(在activity.UserList VAR用户)
{
this._uow.UserRepository.Add(新用户(){用户名=用户});
}
this._uow.Save();
}的CancellationToken);
...略...
}
}
InRequestScope
倒是对象是的Dispose
D在一个请求结束,因此它不能被用于这种情况。 InThreadScope
也放不下因为这将重用UOW几个任务。
你可以做什么虽然是宣布你的 AsyncService
作为内部使用NamedScope扩展的所有对象范围界定对象。
请参阅http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/
I have an MVC3 project that uses Ninject, Entity Framework and the Unit of Work pattern with a Service layer.
My AsyncService class has a function that starts a background task that, as an example, adds users to the User repository. My current problem is that the task only runs correctly for a few seconds before I get an error that the DbContext has been disposed. My database context, which is injected with Ninject's InRequestScope() seems to be getting disposed, as InRequestScope() ties it to HttpContext.
I've read about InThreadScope(), however I'm not sure how to implement it properly in my MVC project.
My Question is: What is the correct way to use Ninject in my Task?
public class AsyncService
{
private CancellationTokenSource cancellationTokenSource;
private IUnitOfWork _uow;
public AsyncService(IUnitOfWork uow)
{
_uow = uow;
}
public void AsyncStartActivity(Activity activity)
{
...snip...
this.cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = this.cancellationTokenSource.Token;
var task = Task.Factory.StartNew(() =>
{
foreach (var user in activity.UserList)
{
this._uow.UserRepository.Add(new User() {UserID = user});
}
this._uow.Save();
}, cancellationToken);
...snip...
}
}
InRequestScope
'd objects are Dispose
d at the end of a request so it can't be used in this case. InThreadScope
also doesn't fit as that would reuse the UoW for several tasks.
What you can do though is declare your AsyncService
as the Scoping Object for all the objects within using the NamedScope extension.
See http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/
这篇关于Ninject范围的问题与任务/线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!