C
C#•5mo ago
N0b0dy

Certain services could not be instantiated due to iss

Hi , I am trying implement Unit of Work design pattern.
C# public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context;
protected readonly DbSet<T> _dbSet;
protected readonly ILogger _logger;
public Repository(DbContext context, ILogger logger)
{
_context = context;
_dbSet = context.Set<T>();
_logger = logger;
}

public virtual async Task<T?> GetByIdAsync(int id)
{
var data = await _dbSet.FindAsync(id);

if (data == null) { return null; }
else { return data; }
}

public virtual async Task<IEnumerable<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}

public virtual async Task AddAsync(IEnumerable<T> entities)
{
await _dbSet.AddRangeAsync(entities);
await _context.SaveChangesAsync();
}

public virtual async Task UpdateAsync(IEnumerable<T> entities)
{
_dbSet.UpdateRange(entities);
await _context.SaveChangesAsync();
}


}

public class DepartmentRepository : Repository<Department>, IDepartmentRepository
{
private readonly DbContext _context;
public DepartmentRepository(DbContext context, ILogger logger) : base(context, logger)
{
_context = context;
}


public override async Task<IEnumerable<Department>> GetAllAsync()
{
try
{
var result = await _dbSet.Where(x => x.IsActive == true).ToListAsync();
return result.AsEnumerable();
}
catch (Exception ex)
{
_logger.LogError((ex), "{Repo} GetAllAsync ", typeof(DepartmentRepository));
return null;
}
}
}

Program.cs
builder.Services.AddScoped<IDepartmentRepository, DepartmentRepository>();
C# public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context;
protected readonly DbSet<T> _dbSet;
protected readonly ILogger _logger;
public Repository(DbContext context, ILogger logger)
{
_context = context;
_dbSet = context.Set<T>();
_logger = logger;
}

public virtual async Task<T?> GetByIdAsync(int id)
{
var data = await _dbSet.FindAsync(id);

if (data == null) { return null; }
else { return data; }
}

public virtual async Task<IEnumerable<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}

public virtual async Task AddAsync(IEnumerable<T> entities)
{
await _dbSet.AddRangeAsync(entities);
await _context.SaveChangesAsync();
}

public virtual async Task UpdateAsync(IEnumerable<T> entities)
{
_dbSet.UpdateRange(entities);
await _context.SaveChangesAsync();
}


}

public class DepartmentRepository : Repository<Department>, IDepartmentRepository
{
private readonly DbContext _context;
public DepartmentRepository(DbContext context, ILogger logger) : base(context, logger)
{
_context = context;
}


public override async Task<IEnumerable<Department>> GetAllAsync()
{
try
{
var result = await _dbSet.Where(x => x.IsActive == true).ToListAsync();
return result.AsEnumerable();
}
catch (Exception ex)
{
_logger.LogError((ex), "{Repo} GetAllAsync ", typeof(DepartmentRepository));
return null;
}
}
}

Program.cs
builder.Services.AddScoped<IDepartmentRepository, DepartmentRepository>();
I am unable to locate the mistake here. Could someone please guide me here?
16 Replies
Pobiega
Pobiega•5mo ago
are you sure you always resolve this as IDepartmentRepository? do you have the actual error message?
N0b0dy
N0b0dyOP•5mo ago
@Pobiega
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: UserServices.Interface.IDepartmentRepository Lifetime: Scoped ImplementationType: UserServices.Repositories.DepartmentRepository': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'UserServices.Repositories.DepartmentRepository'.)'
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: UserServices.Interface.IDepartmentRepository Lifetime: Scoped ImplementationType: UserServices.Repositories.DepartmentRepository': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'UserServices.Repositories.DepartmentRepository'.)'
this is actual error mesage
Pobiega
Pobiega•5mo ago
Ah you should probably not request a DbContext in your repository it should be your actual repository err actual context the services.AddDbContext<YourContextType>(); line adds your context to the DI its THAT type you need to request
N0b0dy
N0b0dyOP•5mo ago
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Already added that line and removed dbcontext from the repo. But same error.
Pobiega
Pobiega•5mo ago
wdym cant be show new DepartmentRepository source
Pobiega
Pobiega•5mo ago
look at your constructor still requesting a DbContext and not ApplicationDbContext
N0b0dy
N0b0dyOP•5mo ago
ok
N0b0dy
N0b0dyOP•5mo ago
this is my base class
N0b0dy
N0b0dyOP•5mo ago
is the base class has any problem?
Pobiega
Pobiega•5mo ago
no, thats fine now. I feel I should mention that this is a bit redundant thou EF already implements Unit of Work AND repository patterns so you are just wrapping a UoW in another UoW
N0b0dy
N0b0dyOP•5mo ago
little bit lost here. could you please elaborate more? i do not need base class repo here?
Pobiega
Pobiega•5mo ago
Well, look at what methods are available on DbSet<T> and see what your code does
public virtual async Task AddAsync(IEnumerable<T> entities)
{
await _dbSet.AddRangeAsync(entities);
await _context.SaveChangesAsync();
}
public virtual async Task AddAsync(IEnumerable<T> entities)
{
await _dbSet.AddRangeAsync(entities);
await _context.SaveChangesAsync();
}
you are literally just calling an existing method, then calling save changes
N0b0dy
N0b0dyOP•5mo ago
make sense
Pobiega
Pobiega•5mo ago
DbSet<T> is a generic repository over T already and guess what ApplicationDbContext is? its your unit of work 🙂 So what I'm trying to say is, if you are just doing this to learn how UOW/repo works, go ahead but please do not actually wrap EFCore with UoW/Repo in a real codebase, because its superfluent UoW/repo makes a lot more sense if you are wrapping a raw database connection, or some other source, but not EF/EFCore
N0b0dy
N0b0dyOP•5mo ago
thanks for the help. it makes a lot of sense.
Want results from more Discord servers?
Add your server