Ninject Scope task with tasks / threads

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... } } 
+8
unit-of-work asp.net-mvc-3 task-parallel-library ninject entity-framework-4
source share
2 answers

InRequestScope 'd Dispose d objects at the end of the request, so it cannot be used in this case. InThreadScope also not suitable, as this will lead to the reuse of UoW for several tasks.

What you can do is declare your AsyncService as a Scope object for all objects that use the NamedScope extension.

See http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/

+5
source share

This is a dirty solution that I used in the past using the ChildKernel plugin (I think Named scope will be much cleaner). I basically create a child core and cover everything that relates to UoW, like a singleton in a child core. Then I create a new child kernel for each task, process UoW, and also commit or rollback.

IAsyncTask is an interface with 1 method, Execute()

 private Task void ExecuteTask<T>() where T:IAsyncTask { var task = Task.Factory.StartNew(() => { var taskKernel = _kernel.Get<ChildKernel>(); var uow = taskKernel.Get<IUnitOfWork>(); var asyncTask = taskKernel.Get<T>(); try { uow.Begin(); asyncTask.Execute(); uow.Commit(); } catch (Exception ex) { uow.Rollback(); //log it, whatever else you want to do } finally { uow.Dispose(); taskKernel.Dispose(); } }); return task; } 
0
source share

All Articles