我需要一些关于我的服务层的建议。假设我有这个模型:
public abstract class Entity
{
public Guid Id {get;set;}
}
public abstract class Document: Entity
{
public virtual ICollection<Attachment> Attachments{get;set;}
}
public class Attachment: Entity
{
Guid ParentEntityId {get;set;}
//some props....
}
public class Note: Document
{
//some props
}
public class Comment: Document
{
//some props
}
假设我有 Notes 和 Comments 的存储库。以下是服务层的示例(TDto 表示扁平化实体的 DTO):
public interface IMainService<TDto>
{
TDto Create(TDto dto);
void Update(TDto dto);
void Delete(Guid, Id);
}
public interface IDocumentService
{
AttachmentDto AddNewAttachment(AttachmentDto dto);
}
public abstract DocumentService<TEntity>: IDocumentService
{
private IRepository<TEntity> _repository;
public DocumentService(IRepository<TEntity> repository)
{
_repository = repository
}
AttachmentDto AddNewAttachment(AttachmentDto dto)
{
var entity = _repository.GetById(dto.ParentId);
//attachment code
_repository.Update(entity)
_repository.UoW.Commit();
.....
}
public class NoteService: DocumentService<Note>, IMainServcie<NoteDto>
{
public NoteService(INoteRepository repository): base(repository)
{
.....
}
}
public class CommentService: DocumentService<Comment>, IMainServcie<CommentDto>
{
public NoteService(INoteRepository repository): base(repository)
{
.....
}
}
虽然这很好用,但我觉得我会在我的应用程序层中复制代码。所以,如果我使用的是 Asp.Net MVC,我可能有一个 Comment 控制器和一个 Note 控制器。我必须创建在每个控制器上创建附件的方法。
我正在想办法分离出 Document 服务,这样我就可以拥有一个 Document 控制器。唯一需要注意的是,我不想将我的实体暴露给应用层。我们的一个想法是使用 TDto 键入文档服务方法,并使用某种工厂来拉入存储库和实体类型。意思是,基于 DTO 类型,我们将查找相关实体可能是一个 switch 语句和为它启动实体类型和存储库。
附加信息: 我在 EF 4.1 中的映射使得有一个表用于 Note_Attachments 和 Comment_Attachments。