我已尝试数天来解决这个问题,但对于ASP.NET MVC这个特定主题的信息似乎非常少。我已经Google了数天,但并没有真正能够解决这个问题。
我有一个三层项目。业务层、数据访问层和UI/ Web层。在DAL中是dbcontext、repository和unit of work。在业务层中有一个包含所有接口和EF模型的域层。在业务层中还有一个服务层,其中包含用于EF模型的DTO以及访问存储库的通用存储库服务。此图片应该可以帮助说明。
我的问题是,我就是无法弄清楚如何使用DTO来传输从业务层获取的数据。
我为DTO创建了服务类。我有一个ImageDTO和模型,以及图像锚点相同。我为每个DTO创建了一个服务类。因此我有一个图像服务和一个锚点服务。这些服务继承自存储库服务,并且目前实现了它们自己的服务。但这大概就是我所做到的了。由于这些服务具有通过IoC接收IUnitOfWork接口的构造函数,我几乎已经陷入困境。
如果我直接从UI引用服务,则一切正常,但我只是无法理解如何使用DTO来在服务层和UI层之间以及反之传输数据。
我的服务层:
业务/服务/DTO
public class AnchorDto
{
public int Id { get; set; }
public int x1 { get; set; }
public int y1 { get; set; }
public int x2 { get; set; }
public int y2 { get; set; }
public string description { get; set; }
public int imageId { get; set; }
public int targetImageId { get; set; }
public AnchorDto(int Id, int x1, int y1, int x2, int y2, string description, int imageId, int targetImageId)
{
// Just mapping input to the DTO
}
}
public class ImageDto
{
public int Id { get; set; }
public string name { get; set; }
public string title { get; set; }
public string description { get; set; }
public virtual IList<AnchorDto> anchors { get; set; }
public ImageDto(int Id, string name, string title, string description, IList<AnchorDto> anchors )
{
// Just mapping input to DTO
}
}
业务/服务/服务
public class RepoService<TEntity> : IRepoService<TEntity> where TEntity : class
{
private IRepository<TEntity> repo;
public RepoService(IUnitOfWork repo)
{
this.repo = repo.GetRepository<TEntity>();
}
public IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
return repo.Get(filter, orderBy, includeProperties);
}
public TEntity GetByID(object id)
{
return repo.GetByID(id);
}
public void Insert(TEntity entity)
{
repo.Insert(entity);
}
public void Delete(object id)
{
repo.Delete(id);
}
public void Delete(TEntity entityToDelete)
{
repo.Delete(entityToDelete);
}
public void Update(TEntity entityToUpdate)
{
repo.Update(entityToUpdate);
}
}
Image Service(图片服务),IImageService接口目前还是空的,直到我想明白需要实现什么为止。
public class ImageService : RepoService<ImageModel>, IImageService
{
public ImageService(IUnitOfWork repo)
: base(repo)
{
}
}
目前我的控制器没有真正工作,并且没有使用服务层,所以我决定不包括它们。一旦我解决了这个问题,我计划使用自动映射将DTO映射到ViewModels。
因此,请任何有足够知识的人给我那个我缺失的想法,这样我就能找出问题所在。
DTOBase
将位于服务层,而EntityBase
将位于业务层。 - Daniel J.G.