2014-07-04 3 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

관련 문제