I have an MVC3 project that uses Ninject, Entity Framework, and a Unit of Work template with a service level.
My AsyncService class has a function that runs a background job, which, for example, adds users to the user repository. My current problem is that the task only runs for a few seconds before I receive an error message that was deleted by DbContext. My database context, which is entered using Ninject InRequestScope (), seems to be made available as InRequestScope () associates it with an HttpContext.
I read about InThreadScope (), but I'm not sure how to implement it correctly 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... } }
unit-of-work asp.net-mvc-3 task-parallel-library ninject entity-framework-4
Jason kulatunga
source share