简体   繁体   中英

Inject Custom UserManager To Controller Net Core 2.1

I'm having problems trying to inject my UserManager to my controller.

This is my custom UserManager:

  public class ApplicationUserManager : UserManager<ApplicationUser>
    {

        public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher,
             IEnumerable<IUserValidator<ApplicationUser>> userValidators,
             IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors,
             IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger)
             : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
            {

            }


        public async Task<ApplicationUser> FindAsync(string id, string password)
        {
            ApplicationUser user = await FindByIdAsync(id);
            if (user == null)
            {
                return null;
            }
            return await CheckPasswordAsync(user, password) ? user : null;
        }
    }

This is my Startup.cs

public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.ConfigureCors();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = Configuration["Jwt:Issuer"],
                        ValidAudience = Configuration["Jwt:Issuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                    };
                });
            // Add framework services.
            services.AddMvc();
            services.AddScoped<ApplicationUserManager>();

            var builder = new ContainerBuilder();
            builder.Populate(services);

            // Registering MongoContext. 
            builder.RegisterType<MongoContext>().AsImplementedInterfaces<MongoContext, ConcreteReflectionActivatorData>().SingleInstance();
            //builder.RegisterType<MongoContext>().As<IMongoContext>();

            //Registering ApplicationUserManager. 

   builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>().SingleInstance();
        //builder.RegisterType<ApplicationUserManager>().As<ApplicationUserManager>().SingleInstance();

where the two important lines are:
builder.RegisterType ApplicationUserManager ().As UserManager ApplicationUser ().SingleInstance();
builder.RegisterType ApplicationUserManager ().As ApplicationUserManager ().SingleInstance;



My controller: ( I tested it with this 2 constructors, getting same error)

 public AccountController(ApplicationUserManager applicationUserManager)
        {
            this.applicationUserManager = applicationUserManager;
        }
        public AccountController(UserManager<ApplicationUser> userManager)
        {
            this.userManager = userManager;
        }

And finally the error:

Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'VotNetMon.ApplicationUserManager' can be invoked with the available services and parameters: Cannot resolve parameter 'Microsoft.AspNetCore.Identity.IUserStore 1[VotNetMon.Entities.ApplicationUser] store' of constructor 'Void .ctor(Microsoft.AspNetCore.Identity.IUserStore 1[VotNetMon.Entities.ApplicationUser], Microsoft.Extensions.Options.IOptions 1[Microsoft.AspNetCore.Identity.IdentityOptions], Microsoft.AspNetCore.Identity.IPasswordHasher 1[VotNetMon.Entities.ApplicationUser], System.Collections.Generic.IEnumerable 1[Microsoft.AspNetCore.Identity.IUserValidator 1[VotNetMon.Entities.ApplicationUser]], System.Collections.Generic.IEnumerable 1[Microsoft.AspNetCore.Identity.IPasswordValidator 1[VotNetMon.Entities.ApplicationUser]], Microsoft.AspNetCore.Identity.ILookupNormalizer, Microsoft.AspNetCore.Identity.IdentityErrorDescriber, Syste m.IServiceProvider, Microsoft.Extensions.Logging.ILogger 1[Microsoft.AspNetCore.Identity.UserManager 1[VotNetMon.Entities.ApplicationUser]])'. at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable 1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)

Thanks in advance

As the error says you have to register the IUserStore and other dependencies that are usually registered by the extensions method for AspNetIdentity.

services.AddIdentity<ApplicationUser, IdentityRole>();

Be aware that this also adds cookie authentication because this is what asp.net identity does. If you persist on doing it with autofac, what is totally legit, you should look here which classes have to be registered.

If you want to use identity and jwt together, here is a good tutorial that guides you through it.

Not directly related:

  • Please always use interfaces, don't inject implementations so don't configure your container to resolve implementations.
  • There is a new way to use autofac and microsoft's ioc together which is preferred. You can find an example here . This is the wanted way for asp.net core >= 2.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM