Reputation: 26917
I'm using LinqToSql for a mvc web application. If lots of people hit the web app at roughly the same time, I'm seeing an An item with the same key has already been added.
error. The stack for this error looks like:
[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
This only happens from my RoleRrovider class, which is a custom implementation of the .net RoleProvider. In there, my ctor gets a repository from Ninject like this:
public CustomRoleProvider()
{
_roleRepository = NinjectMVC3.Resolve<IRoleRepository>();
}
The method that errors:
public override string[] GetRolesForUser(string username)
{
return _roleRepository.GetRolesForUser(username);
}
In my repo is nothing but a linq query which returns the data - the repo instantiates a context internally, nothing is static or shared.
Any ideas why this could be happening?
Upvotes: 1
Views: 1269
Reputation: 7458
I don't know if Ninject has the option to do this, but it should return a new isntance of the required context every time you call resolve.
This is caused by the fact that the EF contexts are not thread safe.
For instance, I use Castle.Windsor as my IoC of choice and it has a LifeStyle option, setting it to Transient instead of Singleton (which is the default) gets the desired behaviour.
Upvotes: 1
Reputation: 3045
private object _lockHandle=new object();
public override string[] GetRolesForUser(string username)
{
lock(_lockHandle){
return _roleRepository.GetRolesForUser(username);
}
}
Upvotes: 0