I was working on one POC application for Clean Architecture with Repository Pattern in .Net core.
Below is my application structure -
Which is very straight forward Clean Architecture plain solution.
As per the guidelines of Clean Architecture, I have created Repository Interfaces (With Generic Repository) in "ECommerce.Application" project and the implementation being done in "ECommerce.Infrastructure" project.
My Generic Repos are like below -
public interface IGenericRepository<T>
where T : BaseEntity
{
T[] Get();
T Get(Guid id);
T Get(Expression<Func<T, bool>> predicate);
T[] GetWithInclude(params Expression<Func<T, object>>[] includes);
T GetWithInclude(Guid id, params Expression<Func<T, object>>[] includes);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Guid id);
void SaveChanges();
}
public class GenericRepository<T> : IGenericRepository<T>
where T : BaseEntity
{
private readonly IApplicationDbContext persistenceContext;
private readonly DbSet<T> dbSet;
protected GenericRepository(IApplicationDbContext persistenceContext)
{
this.persistenceContext = persistenceContext;
dbSet = persistenceContext.GetDbSet<T>();
}
protected virtual Expression<Func<T, bool>> DefaultPredicateBuilder => x => true;
T[] IGenericRepository<T>.Get()
{
return dbSet.Where(DefaultPredicateBuilder).ToArray();
}
And my Concrete Repos are -
public interface IUserRepository : IGenericRepository<User>
{
}
public class UserRepository : GenericRepository<User>, IUserRepository
{
protected UserRepository(IApplicationDbContext persistenceContext) : base(persistenceContext)
{
}
}
And I have one UserService where its using the UserRepository for business rules -
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
this._userRepository = userRepository;
}
And i have injected the dependencies in "ECommerce.WebAPI" project -
var connectionString111 = builder.Configuration["ConnectionString:eCommerceDB"];
builder.Services.AddDbContext<ApplicationDbContext>(opts => opts.UseSqlServer(connectionString111));
builder.Services.AddScoped<IApplicationDbContext, ApplicationDbContext>();
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();
Now when I run my WebAPI project, i am getting issue -
A suitable constructor for type 'ECommerce.Application.Interfaces.Repositories.UserRepository' could not be located.
I have seen couple of posts related to this error, But most of the people are suggesting to do -
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
Unfortunately it didnt work for me, Can anyone please help.
Full Details of the error -
Aucun commentaire:
Enregistrer un commentaire