简体   繁体   English

将自定义UserManager注入Controller Net Core 2.1

[英]Inject Custom UserManager To Controller Net Core 2.1

I'm having problems trying to inject my UserManager to my controller. 我在尝试将UserManager注入控制器时遇到问题。

This is my custom UserManager: 这是我自定义的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 这是我的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()。作为UserManager ApplicationUser().SingleInstance();
builder.RegisterType ApplicationUserManager ().As ApplicationUserManager ().SingleInstance; builder.RegisterType ApplicationUserManager().As ApplicationUserManager().SingleInstance;



My controller: ( I tested it with this 2 constructors, getting same error) 我的控制器:(我使用这2个构造函数对其进行了测试,但得到了相同的错误)

 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 Autofac.Core.DependencyResolutionException:不能使用可用服务和参数调用类型为'VotNetMon.ApplicationUserManager'的'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'找到的构造函数:无法解析参数'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]])'. 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) 在Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext上下文,IEnumerable 1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1参数)在Autofac.Core.Resolving.InstanceLookup.Activate (IEnumerable`1参数)

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. 如错误所述,您必须注册IUserStore和其他依赖项,这些依赖项通常是由AspNetIdentity的扩展方法注册的。

services.AddIdentity<ApplicationUser, IdentityRole>();

Be aware that this also adds cookie authentication because this is what asp.net identity does. 请注意,这也会添加cookie身份验证,因为这是asp.net身份所做的。 If you persist on doing it with autofac, what is totally legit, you should look here which classes have to be registered. 如果您坚持使用autofac这样做是完全合法的,则应在此处查看必须注册哪些类。

If you want to use identity and jwt together, here is a good tutorial that guides you through it. 如果您想同时使用identity和jwt,那么这里是一个指导您完成它的好教程。

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. 有一种新方法可以同时使用autofac和Microsoft的ioc。 You can find an example here . 您可以在此处找到示例。 This is the wanted way for asp.net core >= 2.0. 这是asp.net core> = 2.0的通缉方法。

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

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