2

Ninject를 사용하려고 할 때 여기에서 내 문제를 해결할 수있는 기사를 찾지 못하는 것 같습니다. 웹, 비즈니스 로직 및 데이터 액세스 레이어가 포함 된 간단한 n 계층 솔루션을 만들었습니다. DAL에서 필자는 데이터베이스 (단순 테이블 DB)와 일반 저장소 (IRepositoryItemRepository)의 모델을 다음과 같이 작성했습니다.다중 계층 응용 프로그램의 DbContext에서 Ninject 사용

public interface IRepository<T> where T : class 
{ 
    IQueryable<T> GetAll(); 
} 

이 인터페이스의 구현은 다음과 같습니다. 내 BLL에서

public class ItemRepository : IRepository<Item> 
{ 

    public IQueryable<Item> GetAll() 
    { 
     IQueryable<Item> result; 
     using (GenericsEntities DB = new GenericsEntities()) { 
      result = DB.Set<Item>(); 
     } 
     return result; 
    } 

} 

나는 DataModule, Item 객체와 클래스 (DoWork)이을 사용하는 만들었습니다. 다음과 같이 이러한 봐 ...

public class DataModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind(typeof(IRepository<>)).To<ItemRepository>(); 
    } 

} 

항목 객체

public class Item 
{ 

    DAL.IRepository<DAL.Item> _repository; 

    [Inject] 
    public Item(DAL.IRepository<DAL.Item> repository) { 
     _repository = repository; 
    } 

    public List<DAL.Item> GetItems(){ 

     List<DAL.Item> result = new List<DAL.Item>(); 
     result = _repository.GetAll().ToList(); 
     return result;    

    } 

} 

DoWork 클래스

public DoWork() 
    { 
     var DataKernel = new StandardKernel(new DataModule());    
     var ItemRepository = DataKernel.Get<IRepository<DAL.Item>>(); 

     Item thisItem = new Item(ItemRepository); 
     List<DAL.Item> myList = thisItem.GetItems(); 
    } 

내가 가진 문제는 내가 웹 프로젝트에서이 코드를 사용할 때 "DbContext가 삭제되었습니다"런타임 오류가 발생합니다. 나는 프레임 워크를 이해하기 쉽도록 간단하게 유지하려했지만 DbContext 범위를 올바르게 가져 오는 방법을 이해하지 못했습니다. 나는 여기에 다른 기사를 보았지만 특정 시나리오에 특정한 모든 것이 있으며 기본을 올바르게 얻고 싶다.

누구든지 올바른 방향으로 나를 도울 수 있습니까?

답변

2

당신은 당신이 그것을 폐기하고 있기 때문에 당신이 당신의 ItemRepositoryGetAll 방법을 떠나기 전에 쿼리가 아직 실행되지 않습니다 "DbContext가 배치되어있다"얻고있다. 쿼리는 ToList()이 호출 될 때 GetItems 메서드 내에서 실행됩니다.이 때 해당 데이터 문맥은 해당 using 클로저로 인해 이미 처리됩니다. ItemsIQueryable으로 반환하려면 쿼리를 완료 할 때까지 데이터 컨텍스트를 활성화시켜야합니다.

GenericsEntities을 요청 범위 (사용자가 요청할 때 요청할 경우) 또는 웹 응용 프로그램의 경우 또는 데스크톱 응용 프로그램이고 저장소에 삽입하는 경우 사용자 지정 범위에 바인드 할 것을 제안합니다.

등록

Bind<GenericEntities>().ToSelf().InRequestScope(); 

저장소

public class ItemRepository : IRepository<Item> 
{ 
    private readonly GenericEntities DB; 

    public ItemRepository(GenericEntities db) 
    { 
     this.DB = db;        
    } 

    public IQueryable<Item> GetAll() 
    { 
     return DB.Set<Item>(); 
    } 
} 
+0

의미가 있습니다 - 감사 – TheFrenchDuke

+0

내가 언급하는 것을 잊지. 'InRequestScope'가 제대로 작동하도록 web.config에'OnePerRequest' 모듈을 포함시키는 것을 잊지 마십시오. – mipe34

+0

당신이 내 게시물을 여기에 읽으라고 제안 http://www.planetgeek.ch/2012/05/05/what-is-that-all-about-the-repository-anti-pattern/ 및 http : //www.planetgeek. ch/2012/05/08/the-repository-anti-pattern-clarified / –

관련 문제