简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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