Autofac通用注册

时间:2014-07-04 16:01:40

标签: c# autofac

有没有办法可以做到这样的事情:

var builder = new ContainerBuilder();
builder.Register(c => c.Resolve<DbContext>().Set<TEntity>()).As(IDbSet<TEntity>);

1 个答案:

答案 0 :(得分:0)

当然,甚至还有一种模式。它被称为存储库模式:

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<>));