简体   繁体   English

Autofac通用注册

[英]Autofac generic registration

Is there a way I can accomplish something like this: 有没有办法我可以完成这样的事情:

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

Sure, and there's even a pattern for that. 当然,甚至还有一种模式。 It's called the repository pattern: 这称为存储库模式:

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

You can register it as follows: 您可以按以下方式注册:

builder.RegisterGeneric(typeof(EntityFrameworkRepository<>)).As(typeof(IRepository<>));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM