【发布时间】:2019-09-09 16:49:17
【问题描述】:
我在 .Net core 2.2 中做我的空闲时间项目
我将我的项目分为 4 个部分
1) 数据层 2) 存储层 3) 服务 4) Web-API 层
我有一个模型,让我们以 IPerson 为例。 然后我在这里有通用存储库
class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity, IPhysicalPersonEntity
{
private readonly DataContext _context;
private DbSet<TEntity> _entities;
string errorMessage = string.Empty;
public Repository(DataContext context)
{
_context = context;
_entities = context.Set<TEntity>();
}
public void Delete(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity is null");
}
_entities.Remove(entity);
_context.SaveChanges();
}
public IEnumerable<TEntity> GetAll()
{
return _entities
.AsEnumerable();
}
public TEntity GetByIdentifyNumber(int identifyNumber)
{
return _entities
.SingleOrDefault(e => e.Id == identifyNumber);
}
public void Insert(TEntity entity)
{
if(entity == null)
{
throw new ArgumentNullException("entity is null");
}
_entities.Add(entity);
_context.SaveChanges();
}
public void Remove(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity is null");
}
_entities.Remove(entity);
}
public void SaveChanges()
{
_context.SaveChanges();
}
public void Update(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity is null");
}
var currentEntity = _entities
.SingleOrDefault(e => e.Id == entity.Id);
currentEntity = entity;
_context.SaveChanges();
}
}
正如你提到的第三层是服务,所以我这里有服务
- 添加人员
- 删除此人。
- 编辑人员。
- 找到有 id 的人。
- 添加人员推荐。
- 等
每个服务都是具有单个接口的单个类。 我知道在每个服务中我都应该使用我的存储库对象和方法。
但我的问题是:
- 如何在每个服务中处理一个存储库对象?
- 我不想在每个服务中创建每个存储库对象。 (或者也许这是正确的做法?)
- 在这种情况下,最佳做法是什么?
- 我是否以不正确的方式构建架构?
【问题讨论】:
标签: c# .net asp.net-web-api asp.net-core architecture