question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Extensions.DependencyInjection: "An item with the same key has already been added" exception related to scoped lifestyle

See original GitHub issue

When using the new Extensions.DependencyInjection package with an ASP.NET Core 3.1 web application, if multiple requests come in as soon as the application starts up, I’m seeing ArgumentExceptions with the message “An item with the same key has already been added.” specifying some service with a scoped lifestyle that was being resolved.

Here is an example error log:

[2020-07-01 14:51:50.7450] (ERROR) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: An unhandled exception has occurred while executing the request.
System.ArgumentException: An item with the same key has already been added. Key: NoopClaimsTransformation / IClaimsTransformation
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Castle.MicroKernel.Lifestyle.Scoped.ScopeCache.set_Item(Object id, Burden value)
   at Castle.Windsor.Extensions.DependencyInjection.Scope.ExtensionContainerScope.GetCachedInstance(ComponentModel model, ScopedInstanceActivationCallback createInstance)
   at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
   at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
   at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
   at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)
   at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency)
   at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency)
   at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.TryResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency, Object& value)
   at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context)
   at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)
   at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden)
   at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally)
   at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.<>n__0(CreationContext context, Boolean trackedExternally)
   at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.<>c__DisplayClass4_0.<Resolve>b__0(Action`1 afterCreated)
   at Castle.Windsor.Extensions.DependencyInjection.Scope.ExtensionContainerScope.GetCachedInstance(ComponentModel model, ScopedInstanceActivationCallback createInstance)
   at Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
   at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
   at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
   at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)
   at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, Arguments additionalArguments, IReleasePolicy policy, Boolean ignoreParentContext)
   at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, Arguments arguments, IReleasePolicy policy, Boolean ignoreParentContext)
   at Castle.MicroKernel.DefaultKernel.Resolve(Type service, Arguments arguments)
   at Castle.Windsor.WindsorContainer.Resolve(Type service)
   at Castle.Windsor.Extensions.DependencyInjection.WindsorScopedServiceProvider.ResolveInstanceOrNull(Type serviceType, Boolean isOptional)
   at Castle.Windsor.Extensions.DependencyInjection.WindsorScopedServiceProvider.GetRequiredService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext context, String scheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task`1 matcherTask)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Here is a sample project that reproduces the problem for me. If I set the Requests constant in the client application to 1, then everything works fine, but setting it higher than that causes exceptions to be thrown.

SameKeyTest.zip

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:9 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
minhhutcommented, Sep 8, 2020

I have same issue

1reaction
generik0commented, Sep 9, 2020

Yes it happens on startup because this is when MS resolve a number of services. Like the factories and loggers. They seam to be doing it multi thread on the same scope (but multiple scopes) and this is causing an issue for castle when creating multiple the instances on the same scope. The creation needs to be thread safe, so We only get 1 instance Per scope.

My PR fixes this.

Read more comments on GitHub >

github_iconTop Results From Across the Web

An item with the same key has already been added
Most likely, you have model which contains the same property twice. Perhaps you are using new to hide the base property.
Read more >
Error "An item with the same key has already been added"
This article helps to fix the error "An item with the same key has already been added". Applies to: Windows Server 2012 R2...
Read more >
New 21R2 Instance, "An item with the same key has ...
Any insight would be greatly appreciated. Stack Trace: [ArgumentException: An item with the same key has already been added.] System.ThrowHelper ...
Read more >
Dependency Injection in .NET 6 - Service Lifetimes
When dependencies are injected, both MovieDetailsModel and MovieRepository will receive the same instance of CustomLogger , since it was added ...
Read more >
Getting error "An item with the same key has already been ...
This is happening mainly when i try to right click and run from the Browser application Activity (While not observing when i run...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found