title: Entity framework ASP.NET MVC (sometimes) problems with DbContext.Set and elsewhere
body: <p>I've got a weird problem using ASP.NET in combination with Entity Framework and Unity Container. </p>
  
  <p>This problem <strong>only</strong> occurs after the application has been running from a few hours to a few days. And after this happens it's temporally fixed (again for the same period) by restarting IIS.  </p>
  
  <p>Sometimes the problem gives an exception on trying to inject (using unity-container) a Controller. </p>
  
  <p>Example:</p>
  
  <pre><code>public class PersonController
  {
       private readonly ICrudService&lt;Person&gt; personCrudservice;
  
       public PersonController(ICrudService&lt;Person&gt; personCrudservice) 
       {
           this.personCrudservice = personCrudservice;
       }
  }
  </code></pre>
  
  <p>The exception here is: <code>An error occurred when trying to create a controller of type 'PersonController'. Make sure that the controller has a parameterless public constructor.</code></p>
  
  <p>Of course the controller doesn't have a parameterless constructor, but using unity-container the personCrudservice is injected.  However, this doesn't happen since the <code>dbContext.Set&lt;Person&gt;()</code> method gives the following exception: <code>An item with the same key has already been added.</code> which leads to the exception shown above. </p>
  
  <p>Another example is an exception when trying to load data from the database. Which gives a NullReference exception.  (Again, not all of the time and the data exists in the database)</p>
  
  <p>Can you guys help me tackle the issue?</p>
  
  <p><strong>DataContext.cs</strong>:</p>
  
  <pre><code>public class DataContext : IUnitOfWork, IRepositoryFactory, ICrudServiceFactory
  {
      private const string CONNECTIONSTRING = "Constring";
      private static readonly MedicijnverstrekkingDbContext dbContext = new MedicijnverstrekkingDbContext(CONNECTIONSTRING);
      public DbContext DbContext =&gt; dbContext;
  
      public static volatile Dictionary&lt;string, object&gt; repositories = new Dictionary&lt;string, object&gt;();
  
      public DataContext()
      {
          dbContext.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
      }   
  
      public void SaveChanges()
      {
          dbContext.SaveChanges();
      }
  
      public void Dispose()
      {
          dbContext.Dispose();
      }
  
      public IRepository&lt;T&gt; CreateRepositoryFor&lt;T&gt;() where T : class, IEntity
      {
          var naam = typeof(T).FullName;
          var repos = default(IRepository&lt;T&gt;);
  
          if(repositories.ContainsKey(naam))
          {
              repos = repositories[naam] as IRepository&lt;T&gt;;
          }
          if(repos == null)
          {
              repos = new Repository&lt;T&gt;(dbContext.Set&lt;T&gt;());
  
              repositories[naam] = repos;
          }
          return repos;
      }
  
      ICrudService&lt;T&gt; ICrudServiceFactory.GenerateCrudServiceFor&lt;T&gt;(IUnityContainer unityContainer)
      {
          var icrudServiceType = typeof(ICrudService&lt;T&gt;);
  
          var tService = icrudServiceType.Assembly.GetTypes().Where(t =&gt; icrudServiceType.IsAssignableFrom(t)).FirstOrDefault();
  
          //If predefined crud service exists, create an instance, otherwise create a generic crud service.
          if (tService != null)
          {
              return (ICrudService&lt;T&gt;)Activator.CreateInstance(tService, new object[] { unityContainer.Resolve&lt;IUnitOfWork&gt;(), unityContainer.Resolve&lt;IRepository&lt;T&gt;&gt;() });
          }
          else
          {
              return new GenericCrudService&lt;T&gt;(unityContainer.Resolve&lt;IUnitOfWork&gt;(), unityContainer.Resolve&lt;IRepository&lt;T&gt;&gt;());
          }
      }
  }
  </code></pre>
  
  <p><strong>UnityConfig.cs</strong></p>
  
  <pre><code>public class UnityConfig
  {
      private static readonly Lazy&lt;IUnityContainer&gt; container = new Lazy&lt;IUnityContainer&gt;(() =&gt;
      {
          var container = new UnityContainer();
          RegisterTypes(container);
          return container;
      });
  
      public static IUnityContainer Container =&gt; container.Value;
  
      public static void RegisterTypes(IUnityContainer container)
      {
          RegisterDependencies(container);
  
          System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolverAdapter(container));
          GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
      }
  
      private static void RegisterDependencies(IUnityContainer unityContainer)
      {
          RegisterDataContextAndUnitOfWork(unityContainer);
          RegisterRepositories(unityContainer);
          RegisterAuthenticationDependencies(unityContainer);
      }
  
      private static void RegisterDataContextAndUnitOfWork(IUnityContainer container)
      {
          container.RegisterType&lt;IUnitOfWork, DataContext&gt;(HttpContextLifetimeManager.FromType&lt;DataContext&gt;());
          container.RegisterType&lt;IRepositoryFactory, DataContext&gt;(HttpContextLifetimeManager.FromType&lt;DataContext&gt;());
          container.RegisterType&lt;ICrudServiceFactory, DataContext&gt;(HttpContextLifetimeManager.FromType&lt;DataContext&gt;());
  
      }
  
      private static void RegisterAuthenticationDependencies(IUnityContainer container)
      {
          container.RegisterType&lt;IUserStore&lt;GebruikerModel&gt;, UserStore&gt;(HttpContextLifetimeManager.FromType&lt;UserStore&gt;());
          container.RegisterType&lt;IRoleStore&lt;RoleModel, string&gt;, RoleStore&gt;(HttpContextLifetimeManager.FromType&lt;RoleStore&gt;());
  
          container.RegisterFactory&lt;UserManager&lt;GebruikerModel&gt;&gt;(unityContainer =&gt;
          {
              var userStore = unityContainer.Resolve&lt;IUserStore&lt;GebruikerModel&gt;&gt;();
              var manager = new UserManager&lt;GebruikerModel&gt;(userStore)
              {
                  PasswordHasher = new BcryptPasswordHasher()
              };
              manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider&lt;GebruikerModel&gt;
              {
                  MessageFormat = "Uw inlogcode is {0}."
              });
              manager.SmsService = new SmsService();
              return manager;
          });
  
          container.RegisterType&lt;ICurrentUserProvider, CurrentHttpUserProvider&gt;();
      }
  
      private static void RegisterRepositories(IUnityContainer container)
      {
          var registerRepositoryMethodName = MemberNameHelper.GetActionName(() =&gt; RegisterRepository&lt;IEntity&gt;(container));
          var registerCrudserviceName = MemberNameHelper.GetActionName(() =&gt; RegisterCrudService&lt;IEntity&gt;(container));
          var registerRepositoryMethodInfo = typeof(UnityConfig).GetMethod(registerRepositoryMethodName, BindingFlags.NonPublic | BindingFlags.Static);
          var registerCrudserviceMethodInfo = typeof(UnityConfig).GetMethod(registerCrudserviceName, BindingFlags.NonPublic | BindingFlags.Static);
  
          foreach (var entityType in typeof(IEntity).Assembly.GetTypes().Where(t =&gt; typeof(IEntity).IsAssignableFrom(t)))
          {
              var registerRepositoryMethod = registerRepositoryMethodInfo.MakeGenericMethod(entityType);
              registerRepositoryMethod.Invoke(null, new object[] { container });
  
              var registerCrudserviceMethod = registerCrudserviceMethodInfo.MakeGenericMethod(entityType);
              registerCrudserviceMethod.Invoke(null, new object[] { container });
          }
      }
  
      private static void RegisterRepository&lt;T&gt;(IUnityContainer unityContainer) where T : class, IEntity
      {
          unityContainer.RegisterFactory&lt;IRepository&lt;T&gt;&gt;(
              factory =&gt; factory.Resolve&lt;IRepositoryFactory&gt;().CreateRepositoryFor&lt;T&gt;(),
              HttpContextFactoryLifetimeManager.ForRepository&lt;T&gt;()
          );
      }
  
  
      private static void RegisterCrudService&lt;T&gt;(IUnityContainer unityContainer) where T : class, IEntity
      {
          unityContainer.RegisterFactory&lt;ICrudService&lt;T&gt;&gt;(
              factory =&gt; factory.Resolve&lt;ICrudServiceFactory&gt;().GenerateCrudServiceFor&lt;T&gt;(factory),
              HttpContextFactoryLifetimeManager.ForCrudService&lt;T&gt;()
              );
      }
  }
  </code></pre>
  
  <p>I've been having this problem for weeks now and trying different LifeTimeManagers and also downgrading Unity-Container / Entity Framework didn't help. </p>
  
  <p>Stacktrace: An item with the same key has already been added.</p>
  
  <pre><code>   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
     at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
     at System.Data.Entity.Internal.InternalContext.Set[TEntity]()
     at System.Data.Entity.DbContext.Set[TEntity]()
     at Multitask.COMPANYNAME.DataAccess.EntityFramework.DataContext.CreateRepositoryFor[T]() in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\DataAccess\DataContext.cs:line 50
     --- End of inner exception stack trace ---
     at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
     at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
     at Multitask.COMPANYNAME.WebApplication.Unity.HttpContextFactoryLifetimeManager.GetValue(ILifetimeContainer container) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\WebApplication\Unity\HttpContextFactoryLifetimeManager.cs:line 60
     at Unity.Strategies.LifetimeStrategy.PreBuildUp(BuilderContext&amp; context)
     at Unity.UnityContainer.&lt;&gt;c.&lt;.ctor&gt;b__73_1(BuilderContext&amp; context)
     at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
     at Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
     at Multitask.COMPANYNAME.DataAccess.EntityFramework.DataContext.Multitask.COMPANYNAME.Service.DataAccess.ICrudServiceFactory.GenerateCrudServiceFor[T](IUnityContainer unityContainer) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\DataAccess\DataContext.cs:line 131
     --- End of inner exception stack trace ---
     at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
     at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
     at Multitask.COMPANYNAME.WebApplication.Unity.HttpContextFactoryLifetimeManager.GetValue(ILifetimeContainer container) in C:\Source\Workspaces\Multitask.COMPANYNAME\Multitask.COMPANYNAME\WebApplication\Unity\HttpContextFactoryLifetimeManager.cs:line 70
     at Unity.Strategies.LifetimeStrategy.PreBuildUp(BuilderContext&amp; context)
     at Unity.UnityContainer.&lt;&gt;c.&lt;.ctor&gt;b__73_2(BuilderStrategy[] chain, BuilderContext&amp; context)
     at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
     at Unity.Builder.BuilderContext.Resolve(Type type, String name)
     at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
     at Unity.Processors.ConstructorProcessor.&lt;&gt;c__DisplayClass16_0.&lt;GetResolverDelegate&gt;b__0(BuilderContext&amp; c)
     at Unity.Processors.MemberProcessor`2.&lt;&gt;c__DisplayClass8_0.&lt;GetResolver&gt;b__0(BuilderContext&amp; c)
     at Unity.Processors.MemberProcessor`2.&lt;&gt;c__DisplayClass8_0.&lt;GetResolver&gt;b__0(BuilderContext&amp; c)
     at Unity.Processors.MemberProcessor`2.&lt;&gt;c__DisplayClass8_0.&lt;GetResolver&gt;b__0(BuilderContext&amp; c)
     at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext&amp; context)
     at Unity.UnityContainer.&lt;&gt;c.&lt;.ctor&gt;b__73_2(BuilderStrategy[] chain, BuilderContext&amp; context)
     at Unity.Builder.BuilderContext.Resolve(Type type, String name, InternalRegistration registration)
     at Unity.Builder.BuilderContext.Resolve(Type type, String name)
     at Unity.Builder.BuilderContext.Resolve(ParameterInfo parameter, Object value)
     at Unity.Processors.ConstructorProcessor.&lt;&gt;c__DisplayClass16_0.&lt;GetResolverDelegate&gt;b__0(BuilderContext&amp; c)
     at Unity.Processors.MemberProcessor`2.&lt;&gt;c__DisplayClass8_0.&lt;GetResolver&gt;b__0(BuilderContext&amp; c)
     at Unity.Processors.MemberProcessor`2.&lt;&gt;c__DisplayClass8_0.&lt;GetResolver&gt;b__0(BuilderContext&amp; c)
     at Unity.Processors.MemberProcessor`2.&lt;&gt;c__DisplayClass8_0.&lt;GetResolver&gt;b__0(BuilderContext&amp; c)
     at Unity.Strategies.BuildPlanStrategy.PreBuildUp(BuilderContext&amp; context)
     at Unity.UnityContainer.&lt;&gt;c.&lt;.ctor&gt;b__73_1(BuilderContext&amp; context)
     at Unity.UnityContainer.Unity.IUnityContainer.Resolve(Type type, String name, ResolverOverride[] overrides)
     at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
     --- End of inner exception stack trace ---
     at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
     at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController&amp; controller, IControllerFactory&amp; factory)
     at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
     at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
     at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
     at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously)````
  </code></pre>