Ninject Scope issue with Tasks/Threads

此生再无相见时 提交于 2019-11-29 13:59:05
Remo Gloor

InRequestScope'd objects are Disposed 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/

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<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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!