我正在使用LinqToSql作为一个mvc web应用程序。如果很多人在大致相同的时间点击这个web应用程序,我会看到一个An item with the same key has already been added.错误。此错误的堆栈如下所示:
[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的一个自定义实现。在那里,我的ctor从Ninject获得一个存储库,如下所示:
public CustomRoleProvider()
{
_roleRepository = NinjectMVC3.Resolve<IRoleRepository>();
}错误的方法:
public override string[] GetRolesForUser(string username)
{
return _roleRepository.GetRolesForUser(username);
}在我的repo中,它只不过是一个返回数据的linq查询--回购在内部实例化上下文,没有任何东西是静态的或共享的。
知道为什么会发生这种事吗?
发布于 2012-05-11 07:49:26
我不知道Ninject是否可以这样做,但是每次调用resolve时,它都应该返回所需上下文的一个新的isntance。
这是由于EF上下文不是线程安全造成的。
例如,我使用Castle.Windsor作为我选择的IoC,它有一个LifeStyle选项,将它设置为瞬态,而不是Singleton (这是默认的)获得所需的行为。
发布于 2012-05-11 07:29:51
private object _lockHandle=new object();
public override string[] GetRolesForUser(string username)
{
lock(_lockHandle){
return _roleRepository.GetRolesForUser(username);
}
}https://stackoverflow.com/questions/10547101
复制相似问题