I have Implemented a Generic Repository Pattern and UnitOfWork but I get an InvalidOperationException: Unable to resolve service for type 'UnitOfWork' while attempting to activate MyController
Here is my DBContext:
public class DBContext : DbContext
{
public DBContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Nashrieh2");
}
public DbSet<User> Users { get; set; }
}
Here is User.cs class
public class User
{
[Key]
public string UserID { get; set; }
public string Role { get; set; }
public string UserName { get; set; }
[Required(ErrorMessage = "Choose a password for your account")]
public string Password { get; set; }
}
Here is my Repository Pattern GenericRepository.cs:
public class GenericRepository<T> where T : class
{
internal DBContext _context;
public GenericRepository(DBContext context)
{
this._context = context;
}
public IEnumerable<T> GetList()
{
return _context.Set<T>().ToList();
}
public async Task<IEnumerable<T>> ToListAsync()
{
return await _context.Set<T>().ToListAsync();
}
public virtual T Find(object id)
{
return _context.Set<T>().Find(id);
}
public virtual async Task AddAsync(T entity)
{
await _context.Set<T>().AddAsync(entity);
}
Here is my unit of work:
public class UnitOfWork : IDisposable
{
private DBContext _context;
public UnitOfWork(DBContext context)
{
_context = 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);
}
}
Here is my controller:
public class MyController : Controller
{
private UnitOfWork _unitOfWork;
public MyController(UnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
}
An Exception in occurred
InvalidOperationException: Unable to resolve service for type 'UnitOfWork' while attempting to activate MyController
Aucun commentaire:
Enregistrer un commentaire