User1196679051 posted
I have read Entity Framework uses repositories so we don't need to create our repositories. But how can I eliminate repositories if I don't want to duplicate code and I want to have readable code?
Now I have the DAL project with repositories, for example:
namespace Blog.DAL.Repository
{
public class CommentsRepository : ICommentsRepository
{
private DatabaseContext _context;
public CommentsRepository(DatabaseContext context)
{
_context = context;
}
public IEnumerable<Comment> GetComments(bool isSpam)
{
return _context.Comments.Where(x => x.IsSpam == isSpam).OrderByDescending(x => x.CreatedDate).ToList(); // it can be much more complex query
}
}
}
I have also the BLL project with services, for example:
namespace Blog.BLL.Services
{
public class CommentsService : ICommentsService
{
private ICommentsRepository _commentsRepository;
public CommentsService(ICommentsRepository commentsRepository)
{
_commentsRepository = commentsRepository;
}
public IEnumerable<Comment> DoSomethingWithComments()
{
IEnumerable<Comment> comments = _commentsRepository.GetComments(true);
// ......
return comments;
}
}
}
namespace Blog.BLL.Services
{
public class NotesService : INotesService
{
private INotesRepository _notesRepository;
private ICommentsRepository _commentsRepository;
public NotesService(INotesRepository notesRepository, ICommentsRepository commentsRepository)
{
_notesRepository = notesRepository;
_commentsRepository = commentsRepository;
}
public IEnumerable<Note> DoSomethingWithNotes()
{
IEnumerable<Note> notes = _notesRepository.GetNotes();
IEnumerable<Comment> comments = _commentsRepository.GetComments(true);
// ......
return notes;
}
}
}
Without repositories I don't need to have the DAL project (STRANGE - only the BLL project?) and I have code duplication:
namespace Blog.BLL.Services
{
public class CommentsService : ICommentsService
{
private DatabaseContext _context;
public CommentsService(DatabaseContext context)
{
_context = context;
}
public IEnumerable<Comment> DoSomethingWithComments()
{
IEnumerable<Comment> comments = _context.Comments.Where(x => x.IsSpam == true).OrderByDescending(x => x.CreatedDate).ToList(); // code duplication
// ......
return comments;
}
}
}
namespace Blog.BLL.Services
{
public class NotesService : INotesService
{
private DatabaseContext _context;
public NotesService(DatabaseContext context)
{
_context = context;
}
public IEnumerable<Note> DoSomethingWithNotes()
{
IEnumerable<Note> notes = _context.Notes.OrderBy(x => x.Title).ToList();
IEnumerable<Comment> comments = _context.Comments.Where(x => x.IsSpam == true).OrderByDescending(x => x.CreatedDate).ToList(); // code duplication
// ......
return notes;
}
}
}
So maybe repositories are good solution?