简体   繁体   English

无法访问已处置的 object。\r\n对象名称: 'UserManager`1 - 在调用 CreateAsync(user, model.password) 时

[英]Cannot access a disposed object.\r\nObject name: 'UserManager`1 - while calling CreateAsync(user, model.password)

I am working on .net core porject.我正在研究 .net 核心项目。 My Project structure has 4 projects.我的项目结构有 4 个项目。

  1. Student_Database - (Contains Database table model and ApplicatinDBContext) Student_Database -(包含数据库表 model 和 ApplicinDBContext)
  2. Student_Entities - (Contains All the View side models) Student_Entities - (包含所有视图侧面模型)
  3. Student_Service - (All the Database operation handling from here. It is connected to Database. ex: IUserService and UserService) Student_Service - (所有从这里处理的数据库操作。它连接到数据库。例如:IUserService 和 UserService)
  4. Student_Web - ( Controllers and all the methods, logic along with all the views are in this project) Student_Web - (控制器和所有方法、逻辑以及所有视图都在这个项目中)

I have implemented Entity Framework core.我已经实现了实体框架核心。 And try to using Usermanager for insert data.并尝试使用 Usermanager 插入数据。 Now when I am calling method "CreateAsync" from controller(Student_Web) it works fine and user inserted.现在,当我从控制器(Student_Web)调用方法“CreateAsync”时,它可以正常工作并插入用户。 But I want to implement database operation in Student_Service.但是我想在Student_Service中实现数据库操作。 So when I am calling "CreateAsync" from UserService it gives me error "Cannot access a disposed object.\r\nObject name: 'UserManager`1"因此,当我从 UserService 调用“CreateAsync”时,出现错误“无法访问已处置的 object。\r\n对象名称:'UserManager`1”

I am calling this interface IUserService from controller.我从 controller 调用这个接口 IUserService。 So here is my code in UserService.所以这是我在 UserService 中的代码。

Please help me to solve this.请帮我解决这个问题。

public class UserService : IUserService
{
    #region Properties

    private readonly IDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole<int>> _roleManager;

    #endregion

    #region Consturctor

    public UserService(
        IDbContext context
        , UserManager<ApplicationUser> userManager
        , RoleManager<IdentityRole<int>> roleManager
    {
        _context = context;
        _userManager = userManager;
        _roleManager = roleManager;
    }
    #endregion

    #region Methods
        
    public async Task<bool> Create(NewUsers model)
    {
        bool result = false;
        try
        {
            var user = await _userManager.FindByNameAsync(model.UserName);
            if (user == null)
            {
                model.Password = GeneratePassword();
                user = new ApplicationUser
                {
                    //Id = 10,
                    UserName = model.UserName,
                    Email = model.UserName,
                    AccessFailedCount = 0,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    CreatedBy = 2,
                    CreatedDate = DateTime.UtcNow,
                    Active = false
                };
                    
                var returnResult = await _userManager.CreateAsync(user, model.Password);
                if (returnResult.Succeeded)
                {
                    returnResult = await _userManager.AddToRoleAsync(user, _roleManager.Roles.Where(x=>x.Id == model.RoleId).Select(x => x.Name).FirstOrDefault());
                }
                if (model.CompanyId!= null)
                {
                    foreach (var item in model.CompanyId)
                    {
                        var userMap = new UserCompanyMapping();
                        userMap.UserId = user.Id;
                        userMap.CompanyId = item;
                        _userCompanyMappingRepository.Insert(userMap);
                    }
                }
                result = returnResult.Succeeded;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
        return result;
    }
    #endregion
}

//startup class

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(option =>
        {
            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            option.Filters.Add(new AuthorizeFilter(policy));
        });
        
        services.AddDbContextPool<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentityCore<ApplicationUser>();
        // Register Dependencies extra service
        services.AddAppServices();
            
        services.AddIdentity<ApplicationUser, IdentityRole<int>>(options =>
        {
            options.User.RequireUniqueEmail = true;
            options.Password.RequireNonAlphanumeric = false;
        })
       .AddRoles<IdentityRole<int>>()
       .AddEntityFrameworkStores<ApplicationDbContext>()
       .AddDefaultTokenProviders();

        services.ConfigureApplicationCookie(option =>
        {
            option.LoginPath = "/login";
            option.AccessDeniedPath = "/Login/AccessDenied";
        });

        // Register dependancy
        RegisterAutoMapper(services);
        RegisterServices(services);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.ConfigureRequestPipeline();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            //register all routes
            EngineContext.Current.Resolve<IRoutePublisher>().RegisterRoutes(endpoints);
        });
        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapControllerRoute(
        //        name: "default",
        //        pattern: "{controller=Login}/{action=Index}/{id?}");
        //});
    }

    private void RegisterServices(IServiceCollection services)
    {
        // Get class libraryGetAssembly(ty)
        var serviceLibraries = Assembly.Load("Student.Services")
            .GetTypes()
            .Where(x => x.IsClass && x.GetInterfaces().Any() && x.Namespace.Contains(".Services.Services"))
            .ToList();

        if (serviceLibraries != null && serviceLibraries.Count > 0)
        {
            foreach (var service in serviceLibraries)
            {
                var interfaceType = service.GetInterfaces().FirstOrDefault();
                services.AddScoped(interfaceType, service);
            }
        }
    }

    private void RegisterAutoMapper(IServiceCollection services)
    {
        // Auto Mapper Configurations
        var mappingConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new MappingProfile());
        });

        IMapper mapper = mappingConfig.CreateMapper();
        services.AddSingleton(mapper);
    }
}

//Action controller method



namespace Student.Web.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        private readonly IUserService userService;
        private readonly ICommonService commonService;

        public UserController(
            IUserService userService,
            ICommonService commonService)
        {
            this.userService = userService;
            this.commonService = commonService;
        }

        public IActionResult Index()
        {
            return View();
        }
        
        [HttpGet]
        public IActionResult Create()
        {
            ViewBag.RoleList = commonService.GetRoles().Result;
            ViewBag.CompanyList = commonService.GetCompanies().Result;
            ViewBag.CityList = commonService.GetCities().Result;
            ViewBag.CompanyAccessList = commonService.GetCompanyAccessListMultiCheck().Result;
            return View();
        }

        [HttpPost]
        public IActionResult Create(UserAddModel model)
        {
            if (ModelState.IsValid)
            {
                var response = userService.Create(model);
            }
            return RedirectToAction("Index");
        }
    }
}

The call to your service is never awaited , so it is kind of became fire-and-forget which means the request might ends before the service finishes its job which would cause the requested services to get disposed.永远不会awaited对您的service的调用,因此它有点变成了即fire-and-forget ,这意味着请求可能会在服务完成其工作之前结束,这将导致所请求的服务被处理掉。

To fix that you need to alter your Create Action a little bit by doing the followings:要解决此问题,您需要通过执行以下操作稍微更改您的Create Action

  1. Make your action async and let it return Task<IActionResult> .使您的操作async并让它返回Task<IActionResult>
  2. Await the service.等待服务。
        [HttpPost]
        public async Task<IActionResult> Create(UserAddModel model)
        {
            if (ModelState.IsValid)
            {
                var response = await userService.Create(model);
            }
            return RedirectToAction("Index");
        }

Then it should work just fine.然后它应该工作得很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法访问已处置的对象。\\ r \\ n对象名称:“ ApplicationUserManager” - Cannot access a disposed object.\r\nObject name: 'ApplicationUserManager' 无法访问已处置的对象对象名称:&#39;UserManager`1&#39; - Cannot access a disposed object Object name: 'UserManager`1' 无法访问已处置的 object。 Object 名称:“IServiceProvider”,同时使用后台队列 - Cannot access a disposed object. Object name: 'IServiceProvider' while working with background queue AutoMapper IValueResolver:无法访问已处理的对象。 对象名称:&#39;IServiceProvider&#39; - AutoMapper IValueResolver: Cannot access a disposed object. Object name: 'IServiceProvider' ObjectDisposedException:无法访问已处置的对象。 对象名称:“调度程序” - ObjectDisposedException: Cannot access a disposed object. Object name: 'Dispatcher' C#&#39;无法访问已处置的对象。 对象名称:“ SslStream”。 - C# 'Cannot access a disposed object. Object name: 'SslStream'.' HangFire“无法访问已处置的对象。对象名称:'SqlDelegatedTransaction'” - HangFire "Cannot access a disposed object. Object name: 'SqlDelegatedTransaction'" 无法访问已处置的对象。 对象名称:&#39;tlsxyz&#39; - Cannot access a disposed object. Object name: 'tlsxyz' 无法访问已处置的对象。 对象名称:“ NumericUpDown” - Cannot access a disposed object. Object name: 'NumericUpDown' 获取 System.ObjectDisposedException:无法访问已处置的对象。 对象名称:“RSA”。 在身份服务器 6 中使用手动密钥管理时 - getting System.ObjectDisposedException: Cannot access a disposed object. Object name: 'RSA'. while using manual key management in identity server 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM