小编Add*_*han的帖子

如何解决无法使用范围服务

我已将托管服务添加到我的 .net core 3.1 项目中。但添加托管服务后我面临以下错误。

无法使用范围服务

。在此之前我的项目运行良好。我想为我的项目添加后台服务从数据库获取数据。

启动.cs

services.AddScoped<IScheduleService, ScheduleService>();
services.AddHostedService<TimedHostedService>();
Run Code Online (Sandbox Code Playgroud)

SMhostedService.cs

internal class TimedHostedService : IHostedService, IDisposable
    {
        private readonly Microsoft.Extensions.Logging.ILogger _logger;
        private Timer _timer;
        private IScheduleService _scheduleService;
        public TimedHostedService(ILogger<TimedHostedService> logger, IScheduleService scheduleService)
        {
            _logger = logger;
            _scheduleService = scheduleService;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(10));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working.");
            DateTime todaydate = new DateTime();
            var getAttendanceStatus = …
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core-3.1

5
推荐指数
1
解决办法
4049
查看次数

标签 统计

.net-core ×1

asp.net-core-3.1 ×1

c# ×1