自动通用注册
本文关键字:注册 | 更新日期: 2023-09-27 18:11:24
有没有办法让我完成这样的事情:
var builder = new ContainerBuilder();
builder.Register(c => c.Resolve<DbContext>().Set<TEntity>()).As(IDbSet<TEntity>);
当然,这甚至有一个模式。它被称为存储库模式:
public interface IRepository<TEntity>
{
IQueryable<TEntity> GetAll();
TEntity GetById(Guid id);
}
public class EntityFrameworkRepository<TEntity> : IEntity<TEntity>
{
private readonly DbContext context;
public EntityFrameworkRepository(DbContext context) {
this.context = context;
}
public IQueryable<TEntity> GetAll() {
return this.context.Set<TEntity>();
}
public TEntity GetById(Guid id) {
var item = this.context.Set<TEntity>().Find(id);
if (item == null) throw new KeyNotFoundException(id.ToString());
return item;
}
}
您可以按如下方式注册:
builder.RegisterGeneric(typeof(EntityFrameworkRepository<>)).As(typeof(IRepository<>));