2009-10-29 31 views
0

我在我的應用程序中實現了一個存儲庫模式,並且在我的一些控制器中使用了各種不同的存儲庫。 (否的IoC實現)多個DataContext/EntitiesObject

UsersRepository Users; 
OtherRepository Other; 
Other1Repository Other1; 

public HomeController() 
{ 
    this.Users = new UsersRepository(); 
    this.Other = new OtherRepository(); 
    this.Other1 = new Other1Repository(); 
} 

爲了避免臃腫的控制器構造的未來的問題,我創建了一個包含所有版本庫的類的對象包裝類,我調用這個類的一個實例在我的控制器構造函數。

public class Repositories 
{ 
    UsersRepository Users; 
    OtherRepository Other; 
    Other1Repository Other1; 

    public Repositores() 
    { 
     this.Users = new UsersRepository(); 
     this.Other = new OtherRepository(); 
     this.Other1 = new Other1Repository(); 
    } 
} 

在控制器:

Repositories Reps; 

public HomeController() 
{ 
    this.Reps= new Repositories(); 
} 

這是否會影響我的應用程序現在或將來的表現,當應用程序預計將增長。

每個存儲庫爲10個存儲庫創建自己的DataContext/Entities,即10個不同的DataContexts/Entities。

DataContext/Entitie是一個昂貴的對象,可以創建如此龐大的數量嗎?

回答

3

當您使用它們而不是在構造函數中時,最好只創建存儲庫。

private UsersRepository _usersRepository; 
private UsersRepository UsersRepository 
{ 
    get 
    { 
     if(_usersRepository == null) 
     { 
      _usersRepository = new UsersRepository(); 
     } 
     return _usersRepository; 
    } 
} 

然後使用屬性而不是字段進行訪問。

+0

第二個「私人」應該公開正確嗎? – Omar 2009-10-29 20:51:29

+1

兩者都很好。在你的例子中,你的字段是私有的,所以我把這個屬性變爲私有的。但如果這就是你需要的,它可以公開。 – NotDan 2009-10-29 23:03:10