Is it possible to change UserManager<T>'s lifetime?

Viewed 369

I'm trying to change UserManager<T> lifetime from Scoped to Transient inside the ConfigureServices(IServiceCollection service) but I don't know how to do that. Is it possible or I have to inject IServiceProvider inside every object that needs UserManager<T> and then create a new Scope every time I need to use the UserManager?

1 Answers

You can override the lifetime scopes in the following way or you can create your own user manager:

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>>();
}
Related