4

I have added hosted service my .net core 3.1 project. but after add hosted service i am facing below error.

Cannot consume scoped service

. before this my project working fine. i want to add background service for my project fetching data from database.

startup.cs

services.AddScoped<IScheduleService, ScheduleService>();
services.AddHostedService<TimedHostedService>();

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 = _scheduleService.GetAttendanceStatus(todaydate.Date);
            AttendanceStudent obj = new AttendanceStudent();
            var ss = _scheduleService.AddAttendanceStudent(obj);
        }

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

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

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

IScheduleService.cs

 public interface IScheduleService
    {
        Task<int> AddAttendanceStudent(AttendanceStudent attendanceStudent);
        Task<AttendanceStudent> GetAttendanceStatus(DateTime todaydate);
    }

ScheduleService.cs

public class ScheduleService : IScheduleService
    {
        private readonly IGenericRepository<AttendanceStudent> _studentattendance;
        private readonly IGenericRepository<AttendanceStaff> _staffattendance;
        private readonly IGenericRepository<SchoolDetails> _schoolDetails;
        public ScheduleService(IGenericRepository<AttendanceStudent> studentattendance, IGenericRepository<AttendanceStaff> staffattendance, IGenericRepository<SchoolDetails> schoolDetails)
        {
            _studentattendance = studentattendance;
            _staffattendance = staffattendance;
            _schoolDetails = schoolDetails;

        }
        public async Task<AttendanceStudent> GetAttendanceStatus(DateTime todaydate)
        {
            var ss = await _studentattendance.FindFirstByAsync(x => x.AttendanceDate == todaydate).ConfigureAwait(false);
            return ss;
        }
        public async Task<int> AddAttendanceStudent(AttendanceStudent attendanceStudent)
        {
            var studentResult = await _studentattendance.FindFirstByAsync(x => x.StudentId == attendanceStudent.StudentId && x.ClassDetailsId == attendanceStudent.ClassDetailsId && x.AttendanceDate == attendanceStudent.AttendanceDate).ConfigureAwait(false);
            if (studentResult == null)
            {
                await _studentattendance.InsertAsync(attendanceStudent);
                return attendanceStudent.AttendanceStudentId;
            }
            else
            {
                studentResult.AttendanceType = attendanceStudent.AttendanceType;
                await _studentattendance.UpdateAsync(studentResult).ConfigureAwait(false);
                return studentResult.StudentId;
            }
        }
    }

enter image description here

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Addi Khan
  • 59
  • 1
  • 2
  • 7
  • This article will help you to understand this https://codingblast.com/asp-net-core-dependency-injection-cannot-consume-scoped-service/ – Muhammad Kamran Aslam Jul 15 '20 at 06:39
  • Does this answer your question? [Cannot consume scoped service from singleton](https://stackoverflow.com/questions/57580937/cannot-consume-scoped-service-from-singleton) – Panagiotis Kanavos Jul 15 '20 at 10:14
  • 2
    This is explained in the Background Service docs, in the [Consuming a scoped service in a background task](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio#consuming-a-scoped-service-in-a-background-task) section. You need to inject `IServiceProvider` and explicitly create a scope before trying to create a scoped instance – Panagiotis Kanavos Jul 15 '20 at 10:16
  • 1
    BTW "generic" repositories are an *anti*pattern. A DbSet is *already* a repository, a DbContext is a Unit-of-Work. You gain nothing by adding a lower-level IGenericRepository over a higher-level DbContext and DbSet. Things do become harder to maintain and debug though - for example, the real scoped services here are the DbContexts hiding behind those IGenericRepositories, not ScheduleService. – Panagiotis Kanavos Jul 15 '20 at 10:20
  • A DbContext is a Unit-of-Work - it caches changes and only saves them if `SaveChanges` is called. If it's disposed before that, they changes are discarded. That's why it's typically a scoped service - the scope also controls the UoW's life – Panagiotis Kanavos Jul 15 '20 at 10:21

1 Answers1

-3

try

services.AddSingleton<IScheduleService, ScheduleService>();
Madadinoei
  • 72
  • 7
  • 1
    This won't solve the problem at all. There *is* a need to use scoped services even in singletons, eg using DbContexts – Panagiotis Kanavos Jul 15 '20 at 10:12
  • 1
    While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – E. Zeytinci Jul 15 '20 at 12:21