mercredi 30 juin 2021

GenericRepository NullReferenceException: Object reference not set to an instance of an object [duplicate]

I have Implemented a Generic Repository Pattern and UnitOfWork but I get a Null Reference Exception.

Here is my DBContext:

public class DBContext : DbContext
{
        public DBContext(DbContextOptions<DBContext> options) : base(options)
    {
       
    }
    public DbSet<User> Users { get; set; }
}

I add DBContext to Startup.cs:

   services.AddDbContext<DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")),
                contextLifetime: ServiceLifetime.Transient,
                optionsLifetime: ServiceLifetime.Singleton);

Here is my Repository Pattern GenericRepository.cs:

  public class GenericRepository<T> where T : class

{
    internal DBContext _context;
    internal DbSet<T> dbSet;

    public GenericRepository(DBContext context)
    {
        this._context = context;
        this.dbSet = _context.Set<T>();
    }
   public IEnumerable<T> GetList()
    {
      return  dbSet.ToList();
    }
    public async Task<IEnumerable<T>> ToListAsync()
    {
        return await dbSet.ToListAsync();
    }
    public virtual T Find(object id)
    {
        return dbSet.Find(id);
    }
  public virtual async Task AddAsync(T entity)
    {
         await dbSet.AddAsync(entity);
    }

Here is my unit of work:

public class UnitOfWork : IDisposable
{
   private readonly DBContext _context;
    public GenericRepository<User> Users
    {
        get
        {

            if (this.user == null)
            {
                this.user = new GenericRepository<User>(_context);
            }
            return user;
        }
    }
    public async Task SaveChangesAsync()
    {
        await _context.SaveChangesAsync();
    }
    public void SaveChanges()
    {
        _context.SaveChanges();
    }
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
  

An Exception in in GenericRepository.cs occurred

NullReferenceException: Object reference not set to an instance of an object.

this.dbSet = _context.Set<T>();

Aucun commentaire:

Enregistrer un commentaire