Answer the question
In order to leave comments, you need to log in
What is the problem with UoW working with EntityRepository?
I get the error: ---> System.InvalidOperationException: Unable to resolve service for type 'Project.Data.ProductRepository' while attempting to activate 'Project.Data.UnitOfWork'.
In Startup, two services are connected:
services.AddTransient<IProduct<Product>, ProductRepository>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
public class ProductRepository : IProduct<Product>
{
readonly DataContext _context;
public ProductRepository(DataContext context)
{
_context = context;
}
public async Task<IList<Product>> GetAllAsync()
{
return await _context.Set<Product>().ToListAsync();
}
public async Task<Product> GetIdAsync(int item)
{
return await _context.Set<Product>().FindAsync(item);
}
public async Task<Product> AddAsync(Product item)
{
_context.Set<Product>().Add(item);
await _context.SaveChangesAsync();
return item;
}
public async Task<Product> UpdateAsync(Product item)
{
_context.Entry(item).State = EntityState.Modified;
await _context.SaveChangesAsync();
return item;
}
public async Task<Product> DeleteAsync(int item)
{
Product product = await _context.Set<Product>().FindAsync(item);
if (product == null) return product;
_context.Set<Product>().Remove(product);
await _context.SaveChangesAsync();
return product;
}
}
public class UnitOfWork : IUnitOfWork
{
readonly DataContext _context;
public ProductRepository Products { get; }
public UnitOfWork(DataContext Context,
ProductRepository Products)
{
this._context = Context;
this.Products = Products;
}
public void Commit()
{
_context.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
_context.Dispose();
}
}
Answer the question
In order to leave comments, you need to log in
Your ProductRepository is registered as IRepository<Product>.
UnitOfWork depends on the ProductRepository, which is not registered with IoC
To make it work for you, replace the line
readonly DataContext _context;
public ProductRepository Products { get; }
public UnitOfWork(DataContext Context,
ProductRepository Products)
{
this._context = Context;
this.Products = Products;
}
readonly DataContext _context;
public IRepository<Product> Products { get; }
public UnitOfWork(DataContext context,
IRepository<Product> products) //Самое важное
{
this._context = context;
this.Products = products;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question