2014-07-04 160 views
0

有沒有一種方法,我可以做到這樣的事:Autofac通用註冊

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

回答

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

是IEntity應該是IRepository? –

+0

@JamieLester:當然。修正了。 – Steven