2012-05-11 91 views
1

我使用LinqToSql爲mvc Web應用程序。如果很多人在幾乎同一時間點擊網絡應用程序,我會看到An item with the same key has already been added.錯誤。堆棧此錯誤的樣子:LinqToSql - 具有相同密鑰的項目已被添加

[ArgumentException: An item with the same key has already been added.] 
    System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +12673712 
    System.Data.Linq.DataContext.GetTable(MetaTable metaTable) +286 
    System.Data.Linq.DataContext.GetTable() +100 
    CableSense.Domain.Repository.Concrete.RoleRepository.GetRolesForUser(String userName) in c:\BuildAgent\work\271278ff356daf1\CableSense.Domain\Repository\Concrete\RoleRepository.cs:84 

從我RoleRrovider類,這是.NET RoleProvider的自定義實現情況。在那裏,我的構造函數從Ninject得到一個存儲庫這樣的:

public CustomRoleProvider() 
    { 
     _roleRepository = NinjectMVC3.Resolve<IRoleRepository>(); 
    } 

的方法是錯誤的:

public override string[] GetRolesForUser(string username) 
    { 
     return _roleRepository.GetRolesForUser(username); 
    } 

在我的回購不過是一個LINQ查詢返回的數據 - 回購實例化內部環境,沒有什麼是靜態的或共享的。

任何想法,爲什麼會發生這種情況?

回答

1

我不知道Ninject是否可以選擇這樣做,但它應該在每次調用resolve時返回一個新的所需上下文的事件。

這是由於EF上下文不是線程安全的。例如,我使用Castle.Windsor作爲我選擇的IoC,並且它有一個LifeStyle選項,將它設置爲Transient而不是Singleton(這是默認值)可以獲得所需的行爲。

+0

+1上下文應該表示一個工作單元,所以它在線程之間共享沒有任何意義 – AHM

0
private object _lockHandle=new object(); 

public override string[] GetRolesForUser(string username) 
    { 
lock(_lockHandle){ 
     return _roleRepository.GetRolesForUser(username); 
} 
    } 
相關問題