Usermanager.DbContext already disposed in Middleware
<p>I have the below Middleware in an Asp.Net Core application where I require a <code>UserManager</code> to be injected in it. When I try to query for a user <code>FindByIdAsync</code>, I get the following exception:</p>

<pre><code>ObjectDisposedException: 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 is 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: 'ApplicationDbContext'.
</code></pre>

<hr>

<p>My Middleware:</p>

<pre><code>namespace MyApp
{
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Options;

    public class MyMiddleware&lt;TUser, TRole&gt; 
        where TUser : class where TRole : class 
    {
        private readonly RequestDelegate _next;
        private readonly UserManager&lt;TUser&gt; _userManager;
        private readonly RoleManager&lt;TRole&gt; _roleManager;
        private readonly IOptions&lt;IdentityOptions&gt; _optionsAccessor;

        public UserIdentityMiddleware(RequestDelegate next, UserManager&lt;TUser&gt; userManager, 
            RoleManager&lt;TRole&gt; roleManager, IOptions&lt;IdentityOptions&gt; optionsAccessor)
        {
            _next = next;
            _userManager = userManager;
            _roleManager = roleManager;
            _optionsAccessor = optionsAccessor;
        }

        public async Task Invoke(HttpContext context)
        {
            var user = await _userManager.FindByIdAsync("1");

            var claimsPrincipal = await new UserClaimsPrincipalFactory&lt;TUser, TRole&gt;(
                _userManager, _roleManager, _optionsAccessor).CreateAsync(user);

            context.User.AddIdentities(claimsPrincipal.Identities);

            await _next(context);
        }
    }
}
</code></pre>