问题
I have ASP.NET MVC 3.0 application, with EF Code First for data layer. I have implemented a Unit of work pattern, I’m binding context of the unit of work on HttpContext.Current.Items[SomeKey] collection. Unit of work is created and committed in OnActionExecuting/Executed events on controller. I’m instantiating repositories using Windsor Castle.
Now I need to use Quartz.net to run a job periodically in my app, this job need also use few repositories. The problem is, that in a SchedulerJob implementation, there is no HttpContext available (indeed). How can I instantiate a repository (which takes UnitOfWorkFactory as constructor parameter) from a Quartz.net Job in that case? How can I substitute missing HttpContext? I will probably need to implement another UnitOfWorkFactory, but I’m not sure where I can bind my context and how to register different factory just for Quartz.net thread. Can you please show me a way or pattern? Thank you.
回答1:
The unit of work implementation belongs to the business logic layer and should not depend on a specific presentation layer such as MVC.
I made a custom UnitOfWorkScope that I've used in a couple of projects: http://coding.abel.nu/2012/10/make-the-dbcontext-ambient-with-unitofworkscope/
回答2:
You might want to consider writing your own job factory and injecting your repositories there. I wrote a post on how to do this here. Windsor also has a facitlity for integrating Quartz.net directly.
One last comment... you shouldn't host Quartz.Net in your web app if you are going to schedule long running jobs or if you are going to schedule jobs to run periodically. IIS process recycling will not let your scheduler run properly. A windows service is the way to go.
来源:https://stackoverflow.com/questions/16119057/how-to-implement-a-quartz-net-job-in-asp-net-mvc-with-unitofworkpattern-on-ef-co