【发布时间】:2015-06-02 08:04:41
【问题描述】:
我对@987654323@ 很陌生,并且有一个使用Entity Framework 的网站。每天晚上,我都需要对我的Person 实体做一些工作。
因此我安装了Quartz.Net 并尝试在Global.asax 中以这种方式使用它:
<%@ Application Language="C#" %>
<%@ Import Namespace="Quartz" %>
<%@ Import Namespace="Quartz.Impl" %>
<script runat="server">
private IScheduler Scheduler { get; set; }
void Application_Start(object sender, EventArgs e)
{
Scheduler = StdSchedulerFactory.GetDefaultScheduler();
Scheduler.Start();
IJobDetail dailyReset = JobBuilder.Create<ApplicationJobs.DailyReset>()
.WithIdentity("dailyReset", "group1")
.Build();
ITrigger dailyResetTrigger = TriggerBuilder.Create()
.WithIdentity("dailyResetTrigger", "group1")
.StartAt(DateBuilder.DateOf(3, 0, 0))
.WithSimpleSchedule(x => x
.WithIntervalInHours(24)
.RepeatForever())
.Build()
Scheduler.ScheduleJob(dailyReset, dailyResetTrigger);
}
</script>
然后是我的 ApplicationJobs 类:
public class ApplicationJobs : System.Web.HttpApplication
{
public class DailyReset : IJob
{
public void Execute(IJobExecutionContext context)
{
using (var uow = new UnitOfWork())
{
foreach (Person person in uof.Context.Persons)
{
//do something
}
}
}
}
}
最后是 UnitOfWork:
public class UnitOfWork : IDisposable
{
private const string _httpContextKey = "_unitOfWork";
private MyEntities _dbContext;
public static UnitOfWork Current
{
get { return (UnitOfWork)HttpContext.Current.Items[_httpContextKey]; }
}
public UnitOfWork()
{
HttpContext.Current.Items[_httpContextKey] = this;
}
public MyEntities Context
{
get
{
if (_dbContext == null)
_dbContext = new MyEntities();
return _dbContext;
}
}
}
但是using (var uow = new UnitOfWork()) 不起作用,因为uow 的构造函数中的HttpContext.Current.Items[_httpContextKey] = this; ;我读到HttpContext.Current 在Application_Start 中不可用。
在阅读相关帖子中,尤其是 this one,但我真的不明白我是否需要创建类似 UnitOfWorkScope described here 的东西,或者是否有办法像目前这样。
那么有没有什么干净和安全的方法来安排一些使用我的UnitOfWork 来更新实体的任务?
非常感谢。
【问题讨论】:
标签: c# asp.net entity-framework scheduled-tasks