Ninject Scope issue with Tasks/Threads

前端 未结 2 1663
失恋的感觉
失恋的感觉 2020-12-20 16:46

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 back

2条回答
  •  一向
    一向 (楼主)
    2020-12-20 17:16

    This is a messy solution that I've used in the past using the ChildKernel plugin (I think Named scope would much cleaner). Basically I create a child kernel, and scope everything pertaining to the UoW as singleton in the child kernel. I then create a new child kernel for each Task, handle the UoW, and commit or rollback.

    IAsyncTask is an interface with 1 method, Execute()

    private Task void ExecuteTask() where T:IAsyncTask
    {
    
            var task = Task.Factory.StartNew(() =>
                                                 {
                var taskKernel = _kernel.Get();
                var uow = taskKernel.Get();
                var asyncTask = taskKernel.Get();
    
                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;
    }
    

提交回复
热议问题