問題

我一直在研究一個.net Core api專案,我根據這個例子(解決方案中)實現了一個背景任務here . 我已經為我的api控制器使用了一些全域性異常處理,根據要求,我必須刪除所有嘗試捕獲語句並給出簡單的HttpStatusCodes.

我必須為我的背景任務/任務做同樣的事情,建立一個從任何其他類繼承的全域性異常處理類,並透過記錄異常而不崩潰系統來工作它的“魔力”.我也必須避免每個請求嘗試/捕獲語句.

我的程式碼到目前為止 HostedService

 public class MyHostedService : CustomExceptionFilter, IHostedService
    {
        private Timer _timer;
        private readonly IServiceScopeFactory _scopeFactory;

        private readonly ILogger _logger;

        public SchedulerHostedService(IServiceScopeFactory scopeFactory)
        {
            _scopeFactory = scopeFactory;

            _logger = new LoggerManager();

        }
        public Task StartAsync(CancellationToken cancellationToken)
        {

            _logger.Info("Background Service is starting");
            _timer = new Timer(ExecuteTask, null, TimeSpan.Zero, TimeSpan.FromMinutes(30));
            return Task.CompletedTask;

        }

        private void ExecuteTask(object state)
        {
            _ = ExecuteTaskOperationAsync();
        }



        private async Task ExecuteTaskOperationAsync()
        {
            using (IServiceScope scope = _scopeFactory.CreateScope())
            {
                IAsyncTask service = scope.ServiceProvider
                    .GetRequiredService<IAsyncTask>();
                await service.CustomTaskAsync();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.Info("Background Service is stopping");
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
 

AsyncTask的實施

  internal interface IAsyncTask
    {
        Task CustomTaskAsync();
    }


    public class DbInternalOperation : CustomExceptionFilter, IAsyncTask
    {
        private readonly MyDbContext _context;

        private readonly ILogger _logger;
        public DbInternalOperation(MyDbContext context)
        {
            _context = context;

            _logger = new Logger();

        }

        public async Task CustomTaskAsync()
        {

            //All db logic to update some records based on date.           
           throw new Exception("Test");

                _logger.Info($"Scheduled operation started");

               //Some code for dbcontext 
                await _context.SaveChangesAsync();


                _logger.Info($"Scheduled operation finished");


        }
 

我的過濾器

 public class CustomExceptionFilter : IExceptionFilter
{

    public void OnException(ExceptionContext context)
     {
        //Some logic for handling exceptions.
     }
}
 

在我的Startup.cs中服務

 services.AddHostedService<MyHostedService>();
services.AddScoped<IAsyncTask, DbInternalOperation >();
services.AddMvc(options=>options.Filters.Add(new CustomExceptionFilter()));
 

我期待系統在’OnException’方法中丟擲異常並完成其工作,但沒有.

我的結構在這裡有什麼問題? 是否可以從繼承自IExceptionFilter的任何服務中捕獲任何異常? 如果有人可以提供一個異常過濾器的基本實現,用於我的背景任務而無需嘗試/捕獲,我將不勝感激.

  最佳答案

  相同標籤的其他問題

c#asp.net-corescheduled-tasks