Usermanager.DbContext already hosted in middleware

I have the following middleware in an Asp.Net Core application where I need to enter UserManager. When I try to request a user FindByIdAsync, I get the following exception:

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'.

My middleware:

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<TUser, TRole> 
        where TUser : class where TRole : class 
    {
        private readonly RequestDelegate _next;
        private readonly UserManager<TUser> _userManager;
        private readonly RoleManager<TRole> _roleManager;
        private readonly IOptions<IdentityOptions> _optionsAccessor;

        public UserIdentityMiddleware(RequestDelegate next, UserManager<TUser> userManager, 
            RoleManager<TRole> roleManager, IOptions<IdentityOptions> 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<TUser, TRole>(
                _userManager, _roleManager, _optionsAccessor).CreateAsync(user);

            context.User.AddIdentities(claimsPrincipal.Identities);

            await _next(context);
        }
    }
}
+2
source share
1 answer

- , Singleton, , , UserManager, , Startup.ConfigureServices, UserManager, dbContext, .

, , , .

, UserManager, , Invoke, :

var userManager = context.RequestServices.GetService(UserManager<TUser>);

, , ,

, servicelocator, , UserManager , , ,

, , , Invoke , :

public async Task Invoke(HttpContext context, UserManager<TUser> userManager)
{
    ...
}

, , , TUser

+3

Source: https://habr.com/ru/post/1655043/


All Articles