title: Dependency Injection error with OpenIddict
body: <p>I have done quite a bit of searching but have come up empty for an answer.  I am getting a error when using the <code>IOpenIddictScopeManager</code> and <code>IOpenIddictApplicationManager</code> about the connection disposing a connection with Dependency Injection.</p>
  <p>The following is the error:</p>
  <blockquote>
  <p>Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.</p>
  </blockquote>
  <p>Stack trace:</p>
  <pre><code>System.ObjectDisposedException
    HResult=0x80131622
    Message=Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
  Object name: 'IdentDbContext'.
    Source=Microsoft.EntityFrameworkCore
    StackTrace:
     at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
     at Microsoft.EntityFrameworkCore.DbContext.&lt;SaveChangesAsync&gt;d__54.MoveNext()
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
     at OpenIddict.EntityFrameworkCore.OpenIddictEntityFrameworkCoreScopeStore`3.&lt;CreateAsync&gt;d__14.MoveNext()
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at OpenIddict.Core.OpenIddictScopeManager`1.&lt;CreateAsync&gt;d__15.MoveNext()
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
     at OpenIddict.Core.OpenIddictScopeManager`1.&lt;CreateAsync&gt;d__16.MoveNext()
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Threading.Tasks.ValueTask`1.get_Result()
     at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
     at OpenIddict.Core.OpenIddictScopeManager`1.&lt;OpenIddict-Abstractions-IOpenIddictScopeManager-CreateAsync&gt;d__47.MoveNext()
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Threading.Tasks.ValueTask`1.get_Result()
     at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
     at IdentityApi.WebApi.Controllers.OpenIDManagementController.&lt;CreateScopeAsync&gt;d__4.MoveNext() in E:\Source\Workspaces\Identity\IdentityApi\IdentityApi.WebApi\Controllers\OpenIDManagementController.cs:line 45
  
    This exception was originally thrown at this call stack:
      [External Code]
      IdentityApi.WebApi.Controllers.OpenIDManagementController.CreateScopeAsync(IdentityApi.WebApi.Models.AdministrationModels.ScopePostInputModel, System.Threading.CancellationToken) in OpenIDManagementController.cs
  </code></pre>
  <p>In my controller I have the following constructor and method that is throwing the error:</p>
  <pre class="lang-cs prettyprint-override"><code>        private readonly IOpenIddictApplicationManager _applicationManager;
          private readonly IOpenIddictScopeManager _scopeManager;
  
          public OpenIDManagementController(IOpenIddictApplicationManager applicationManager, IOpenIddictScopeManager scopeManager)
          {
              _applicationManager = applicationManager;
              _scopeManager = scopeManager;
          }
  
          // Create a scope
          [HttpPost(&quot;CreateScopeAsync&quot;, Name = nameof(CreateScopeAsync))]        
          public async void CreateScopeAsync(ScopePostInputModel scopeInput, CancellationToken cancellationToken)
          {            
              if (await _scopeManager.FindByNameAsync(scopeInput.Name, cancellationToken) is null)
              {
                  var scopeToAdd = new OpenIddictScopeDescriptor
                  {
                      Name = scopeInput.Name,
                      Description = scopeInput.Description,
                      DisplayName = scopeInput.DisplayName
                  };
  
                  var createResult = await _scopeManager.CreateAsync(scopeToAdd, cancellationToken);  // This errors out for dependancy injection
              }
              else
              {
                  // error here
              }
          }
  </code></pre>
  <p>Here is the configuration section of my Statup.cs:</p>
  <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
          {
              services.AddControllers();
              services.AddRazorPages();
  
              services.AddDbContext&lt;IdentDbContext&gt;(options =&gt;
              {
                  options.UseSqlServer(
                      Configuration.GetConnectionString(&quot;IdentityDB&quot;));
  
                  options.UseOpenIddict();
              });
              services.AddIdentity&lt;ApplicationUsers, ApplicationRoles&gt;(config =&gt;
              {
                  config.SignIn.RequireConfirmedEmail = true;
                  config.SignIn.RequireConfirmedAccount = true;
                  config.User.RequireUniqueEmail = true;
                  config.Lockout.MaxFailedAccessAttempts = 3;
              }).AddEntityFrameworkStores&lt;IdentDbContext&gt;()
              .AddUserStore&lt;ApplicationUserStore&gt;()
              .AddRoleStore&lt;ApplicationRoleStore&gt;()
              .AddRoleManager&lt;ApplicationRoleManager&gt;()
              .AddUserManager&lt;ApplicationUserManager&gt;()
              .AddErrorDescriber&lt;ApplicationIdentityErrorDescriber&gt;()
              .AddDefaultTokenProviders()
              .AddDefaultUI();
  
              services.AddDataLibrary();
              
              services.Configure&lt;IdentityOptions&gt;(options =&gt;
              {
                  options.ClaimsIdentity.UserNameClaimType = Claims.Name;
                  options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
                  options.ClaimsIdentity.RoleClaimType = Claims.Role;
              });
  
              services.AddOpenIddict()
                  .AddCore(options =&gt;
                  {
                      options.UseEntityFrameworkCore()
                      .UseDbContext&lt;IdentDbContext&gt;();
                  })
                  .AddServer(options =&gt;
                  {
                      options.AllowClientCredentialsFlow()
                      .AllowAuthorizationCodeFlow()
                      .RequireProofKeyForCodeExchange();
                      options.SetAuthorizationEndpointUris(&quot;/api/Authorization/Authorize&quot;)
                      .SetTokenEndpointUris(&quot;/Token&quot;);
                      
                      options.RegisterScopes(Scopes.OpenId, Scopes.Email, Scopes.Profile, Scopes.Roles, &quot;DatabaseName&quot;);
  
                      options.SetIssuer(new Uri(Configuration[&quot;Jwt:Issuer&quot;]));
  
                      options.AcceptAnonymousClients();
  
                      options.DisableAccessTokenEncryption();
  
                      
                      options.AddDevelopmentEncryptionCertificate()
                            .AddDevelopmentSigningCertificate();
  
                      options.UseAspNetCore()
                             .EnableAuthorizationEndpointPassthrough()
                             .EnableTokenEndpointPassthrough();
                  })
                  .AddValidation(options =&gt;
                  {
                      options.UseLocalServer();
  
                      options.UseAspNetCore();
                  });
              services.AddHostedService&lt;TestData&gt;();  // For development only.
          }
  </code></pre>
  <p>I am not sure what I missed, but no matter what changes I have made I still receive the same error.  Any thoughts on how to correct this error?</p>