@lucky4

В чем проблема работы UoW с EntityRepository?

Получаю ошибку: ---> System.InvalidOperationException: Unable to resolve service for type 'Project.Data.ProductRepository' while attempting to activate 'Project.Data.UnitOfWork'.

В Startup, подключены два сервиса:
services.AddTransient<IProduct<Product>, ProductRepository>();
services.AddTransient<IUnitOfWork, UnitOfWork>();


Код Repository:
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;
        }
    }


И вот код UoW:
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();
        }
    }
  • Вопрос задан
  • 103 просмотра
Решения вопроса 1
vabka
@vabka Куратор тега ASP.NET
Токсичный шарпист
У вас ProductRepository зарегистрирован как IRepository<Product>.
UnitOfWork зависит от ProductRepository, который не зарегистрирован в IoC

Чтобы у вас всё заработало замените строку
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;
        }


Но вообще UoW и Repository тут лишние, тк EF и так сам по себе реализует оба паттерна.
Отвязаться от EF таким образом вы всё равно не сможете
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы