特定の種類のエンティティの共通サービスレイヤー(EF 4.1を使用)を手伝ってください。
-
28-10-2019 - |
質問
サービスレイヤーに関するアドバイスが必要です。私がこのモデルを持っているとしましょう:
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
}
メモやコメントのリポジトリがあるとしましょう。以下は、サービスレイヤーの例です(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を使用していた場合、コメントコントローラーとメモコントローラーがある場合があります。各コントローラーに添付ファイルを作成する方法を作成する必要があります。
ドキュメントコントローラーを手に入れることができるように、ドキュメントサービスを分離する方法を考えようとしています。唯一の注意点は、エンティティをアプリレイヤーにさらすことを望まないことです。ドキュメントサービスメソッドをTDTOで入力し、ある種の工場を使用してリポジトリとエンティティの種類をプルすることでした。エンティティタイプとリポジトリを起動します。
追加情報:EF 4.1の私のマッピングは、Note_AttachmentsとComment_Attachmentsのテーブルがあるようなものです。
解決
私がやったことは、サービス工場を使用して私が望んでいたサービスを取得することでした。また、IdocumentserviceにGenricを追加しました。 Unityコンテナを使用しています。このようなもの:
public static class ServiceFactory
{
public static Services.IDocumentService<TDto> GetDocumentService<TDto>() where TDto : IBridgeDto
{
var dtoName = typeof(TDto).Name;
IDocumentService<TDto> retrunService = null;
switch (dtoName)
{
case "NoteDto":
retrunService = (IDocumentService<TDto>) container.Resolve<INoteService>();
break;
}
return retrunService;
}
}
もうすぐリファクタリングしていますが、これは少なくとも、アプリから私のサービスレイヤーを少し抽象化します。
所属していません StackOverflow