【问题标题】:Is it possible to change UserManager<T>'s lifetime?是否可以更改 UserManager<T> 的生命周期?
【发布时间】:2023-03-03 03:05:01
【问题描述】:

我正在尝试将ConfigureServices(IServiceCollection service) 中的UserManager&lt;T&gt; 生命周期从Scoped 更改为Transient,但我不知道该怎么做。是否有可能或者我必须在每个需要UserManager&lt;T&gt; 的对象中注入IServiceProvider,然后每次我需要使用 UserManager 时创建一个新的 Scope?

【问题讨论】:

    标签: asp.net-core asp.net-identity


    【解决方案1】:

    您可以通过以下方式覆盖生命周期范围,也可以创建自己的用户管理器:

    public void ConfigureServices(IServiceCollection services)
    {
      var connectionString = Configuration.GetConnectionString("DefaultConnection");
    
      services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(connectionString), ServiceLifetime.Transient);
    
      services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
      var userManagerServiceDescriptor =
        services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(UserManager<ApplicationUser>));
      services.Remove(userManagerServiceDescriptor);
    
      var userStoreServiceDescriptor =
        services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IUserStore<ApplicationUser>));
      services.Remove(userStoreServiceDescriptor);
    
      services.AddTransient<DbContext, ApplicationDbContext>();
      services.AddTransient<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
      services.AddTransient<UserManager<ApplicationUser>>();
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2012-02-18
      相关资源
      最近更新 更多