第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

具有DbContext的服務(wù)器端計(jì)時(shí)器

具有DbContext的服務(wù)器端計(jì)時(shí)器

C#
繁星點(diǎn)點(diǎn)滴滴 2021-03-29 17:13:45
我想讓計(jì)時(shí)器在每60秒運(yùn)行一次method()的服務(wù)器上運(yùn)行現(xiàn)在我已經(jīng)完成了-使用以下代碼public class Alarm{    public Alarm(AppDbContext _db)    {        db = _db;    }    private static Timer aTimer;    private AppDbContext db;    public void StartTimerEvent()    {        // Create a timer and set a 60 second interval.        aTimer = new Timer();        aTimer.Interval = 60000;        // Hook up the Elapsed event for the timer.         aTimer.Elapsed += (source, e) => CheckDBEvents(source, e);        // Have the timer fire repeated events (true is the default)        aTimer.AutoReset = true;        // Start the timer        aTimer.Enabled = true;    }    private void CheckDBEvents(Object source, ElapsedEventArgs e)    {        //get data from db with matching queries        List<Grocery> DataList = db.Grocery.Where(G => G.basic).Select(G => new Grocery        {            Id = G.Id,            Timeout = G.Timeout        }).ToList();    }}method()是CheckDBEvents(),它的作用是訪問(wèn)dbcontext實(shí)例,并尋找一些數(shù)據(jù)保存到本地常量變量Called DataList中。問(wèn)題:每次我嘗試將上下文(Dbcontext)實(shí)例(在控制器或任何其他類(lèi)中)傳遞給CheckDBEvents()方法時(shí),都會(huì)處理該上下文-DbContext Disposed Exception。呼叫者,召集者var t = new Alarm(db);t.StartTimerEvent();我的輪胎:-使警報(bào)成為靜態(tài)類(lèi):現(xiàn)在,如果我能夠做到這一點(diǎn),那將是驚人的……但是無(wú)法在DbContext上進(jìn)行操作,因?yàn)槟鸁o(wú)法在靜態(tài)類(lèi)中調(diào)用DbContext上的實(shí)例,因此您必須將其傳遞給調(diào)用它的人,這會(huì)導(dǎo)致相同的問(wèn)題: db已處置且未通過(guò)        public static void StartTimerEvent(AppDbContext db)    {    .....     // Hook up the Elapsed event for the timer.      aTimer.Elapsed += (source, e) => CheckDBEvents(source, e, db      //DbContext is Disposed here and     //don't get passed'     );而且常量類(lèi)和Dbcontext與我所閱讀的內(nèi)容相處得不太好。長(zhǎng)話短說(shuō) -我想保留的DbContext實(shí)例在另一個(gè)階級(jí),而不是控制器。沒(méi)有被處置。如果有人知道如何執(zhí)行此操作或有服務(wù)器端計(jì)時(shí)器的源代碼或類(lèi)似的內(nèi)容,請(qǐng)發(fā)表評(píng)論,我被困了2天
查看完整描述

2 回答

?
猛跑小豬

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊

我會(huì)厭倦將DbContext直接注入到托管服務(wù)中。


我的建議是注射IServiceScopeFactory。并且每次您的警報(bào)響起時(shí),都創(chuàng)建一個(gè)作用域,并僅針對(duì)該CheckDBEvents操作解析DbContext 。


甚至您與其他問(wèn)題的鏈接也建議您這樣做。這樣,您可以更優(yōu)雅地管理DbContext生存期。


像這樣的東西:


var scope = serviceFactory.CreateScope();

await using var dbContext = scope.ServiceProvider.GetService<MyDbContext>();


查看完整回答
反對(duì) 回復(fù) 2021-04-10
  • 2 回答
  • 0 關(guān)注
  • 186 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)