title: Asp.Net Core - Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'
body: <p>I am experiencing a failure with my Asp.Net Core 1.1 app running on Ubuntu 16.04 LTS.</p>
  
  <p>Usually, after a period of inactivity, when I click somewhere on a loaded site to trigger a controller, the website does not finish loading. I see the controller call timing out after 15 minutes on a first function which is supposed to fetch an object from a database (even though MySql timeout is set to 2 minutes in the connection string):</p>
  
  <pre><code>   at Frontend.Repository.WebsiteSettingsRepository.Find(String id, Boolean getRelated)
     at Frontend.Controllers.HomeController.Index()
  </code></pre>
  
  <p>This is the full exception I am getting:</p>
  
  <pre><code>fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
    An unhandled exception has occurred: Connect Timeout expired.
  MySql.Data.MySqlClient.MySqlException: Connect Timeout expired. ---&gt; System.ObjectDisposedException: Cannot access a disposed object.
  Object name: 'System.Net.Sockets.Socket'.
     at System.Net.Sockets.Socket.BeginConnect(IPAddress address, Int32 port, AsyncCallback requestCallback, Object state)
     at System.Net.Sockets.TcpClient.BeginConnect(IPAddress address, Int32 port, AsyncCallback requestCallback, Object state)
     at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions)
     at System.Net.Sockets.TcpClient.ConnectAsync(IPAddress address, Int32 port)
     at MySql.Data.Serialization.MySqlSession.&lt;OpenTcpSocketAsync&gt;d__30.MoveNext()
     --- End of inner exception stack trace ---
     at MySql.Data.Serialization.MySqlSession.&lt;OpenTcpSocketAsync&gt;d__30.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at MySql.Data.Serialization.MySqlSession.&lt;ConnectAsync&gt;d__22.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at MySql.Data.MySqlClient.ConnectionPool.&lt;GetSessionAsync&gt;d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at MySql.Data.MySqlClient.MySqlConnection.&lt;CreateSessionAsync&gt;d__57.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at MySql.Data.MySqlClient.MySqlConnection.&lt;OpenAsync&gt;d__11.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at MySql.Data.MySqlClient.MySqlConnection.Open()
     at Microsoft.EntityFrameworkCore.Storage.Internal.MySqlRelationalConnection.Open()
     at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable.Enumerator.BufferlessMoveNext(Boolean buffer)
     at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.&lt;_ShapedQuery&gt;d__3`1.MoveNext()
     at Microsoft.EntityFrameworkCore.Query.Internal.MySqlQueryingEnumerable`1.MySqlEnumerator.MoveNext()
     at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
     at lambda_method(Closure , QueryContext )
     at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.&lt;&gt;c__DisplayClass20_0`1.&lt;CompileQueryCore&gt;b__0(QueryContext qc)
     at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
     at Frontend.Repository.WebsiteSettingsRepository.Find(String id, Boolean getRelated)
     at Frontend.Controllers.HomeController.Index()
     at lambda_method(Closure , Object , Object[] )
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeActionMethodAsync&gt;d__27.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeNextActionFilterAsync&gt;d__25.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeNextResourceFilter&gt;d__22.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeAsync&gt;d__20.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.AspNetCore.Builder.RouterMiddleware.&lt;Invoke&gt;d__4.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.&lt;Invoke&gt;d__18.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.&lt;Invoke&gt;d__18.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.&lt;Invoke&gt;d__3.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.&lt;Invoke&gt;d__4.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.&lt;Invoke&gt;d__6.MoveNext()
  </code></pre>
  
  <p>I use the dependency injection to pass the context to the repositories:</p>
  
  <pre><code>    services.AddDbContext&lt;DatabaseConnector&gt;(options =&gt;
      {
          options.UseMySql(mysqlConfigString);
          options.ConfigureWarnings(warnings =&gt; warnings.Throw(CoreEventId.IncludeIgnoredWarning));
      });
  </code></pre>
  
  <p>in the constructor:</p>
  
  <pre><code>    public WebsiteSettingsRepository(DatabaseConnector dbContext)
      {
          _db = dbContext;
      }
  </code></pre>
  
  <p>The DatabaseConnector has a few DbSets, for example:</p>
  
  <pre><code>public DbSet&lt;UserModel&gt; Users { get; set; }
  </code></pre>
  
  <p>As far as I understand, the database context also uses the default memory cache for temporary results.</p>
  
  <p>The database is used for fetching details only for the frontend side, so the amount of the transferred data is small (the core data is stored in a separate distributed cluster).</p>
  
  <p>I was suspecting the number of the connections in the pool might be exceeded, but this should give a different error. There should not be any connection leak, because the connection is never explicitly opened. Now, I am thinking it might be OS-specific. Most of the times the website works fine though. Any ideas? I already tried scaling up a vm.</p>
  
  <p>[Update]</p>
  
  <p>The controller's code, it's not even async, it only uses multiple repositories:</p>
  
  <pre><code>    public IActionResult Index()
      {
          var activity = new CustomLog("HomeController.Index");
          try
          {
              (a couple of non-db lines, the next one throws)
              var newsSpeed = _settingsRepository.Find(WebsiteSetting.NewsSpeed.ToString());
              (...)
              if (newsSpeed != null &amp;&amp; newsSpeed.Value != null)
              {
                  tableConfig.NewsScrollSpeed = int.Parse(newsSpeed.Value);
              }
  
              (a lot of similar stuff there...)
  
              return View(tableConfig);
          }
          catch(Exception e)
          {
              activity.Finish(e);
              throw;
          }
      }
  </code></pre>
  
  <p>SettingRepository is set through DI in a controller's constructor and looks like this:</p>
  
  <pre><code>private readonly IGenericRepositoryNamed&lt;WebsiteSettingsModel, WebsiteSettingsViewModel&gt; _settingsRepository;
  </code></pre>
  
  <p>It's created in Startup.cs:</p>
  
  <pre><code>services.AddScoped&lt;IGenericRepositoryNamed&lt;WebsiteSettingsModel, WebsiteSettingsViewModel&gt;, WebsiteSettingsRepository&gt;();
  </code></pre>