任务/主题的Ninject Scope问题 [英] Ninject Scope issue with Tasks/Threads
问题描述
我的AsyncService类有一个启动背景的功能作为示例的任务将用户添加到用户存储库。
我目前的问题是,任务只能运行正确几秒钟,然后我收到一个DbContext已经被处理的错误。
我的数据库上下文,注入Ninject的InRequestScope()似乎被处理,因为InRequestScope()将其绑定到HttpContext。
我已经阅读关于InThreadScope(),但是我不知道如何在我的MVC项目中正确实现它。
我的问题是:在我的任务?
public class AsyncService
{
private CancellationTokenSource cancelTokenSource;
private IUnitOfWork _uow;
public AsyncService(IUnitOfWork uow)
{
_uow = uow;
}
public void AsyncStartActivity(Activity activity)
{
... snip ...
this.cancellationTokenSource = new CancellationTokenSource();
var cancellerToken = this.cancellationTokenSource.Token;
var task = Task.Factory.StartNew(()=>
{
foreach(activity.UserList中的var用户)
{
this._uow.UserRepository .Add(new User(){UserID = user});
}
this._uow.Save();
},cancelToken);
... snip ...
}
}
InRequestScope
'd对象是在请求结束时处理
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 Scope问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!