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();
}
}
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;
}