Search code examples
c#asp.netclean-architectureonion-architecture

How to correctly establish the type argument to CancellationToken in Net Core?


I'm developing a clean Architecture's services on Net Core. However when I refactor the methods, it return me the error cs0411. more specifically in the 'GetSubjectById' method when the Cancellation Token is usage and it didnt provide the type argument.

IRepository.cs #this is the repository interfaces that contain controller's method

public interface IRepository
    {
        Task<Subject> GetSubjectById(int id, CancellationToken CancellationToken);           
    }

MethodRepository.cs #this is the methods for the below Interface

  public class SubjectRepository : ISubjectRepository
    {
        private readonly dbContext _context;
        private ISubjectRepository _subject;

        
         public ISubjectRepository Subject {
            get {
                if(_subject == null)
                {
                    _subject = new SubjectRepository(_context);
                }
                return _subject;
            }
         }
        public SubjectRepository(dbContext context)
        {
            _context = context;
        }
        public async Task<Subject> GetSubjectById(int id, CancellationToken cancellationToken)
        {
            return  _context.Subjects.FirstOrDefault(o => o.StudentId == id, cancellationToken) #This code line cause the error cs0411;
            
        }
}

If anyone could bring me some, I'd be really grateful.


Solution

  • It's just because FirstOrDefault doesn't have CancellationToken parameter, but FirstOrDefaultAsync does. Try this

        public Task<Subject> GetSubjectById(int id, CancellationToken cancellationToken)
        {
            return  _context.Subjects.FirstOrDefaultAsync(o => o.StudentId == id, cancellationToken)
            
        }