繁体   English   中英

将自定义UserManager注入Controller Net Core 2.1

[英]Inject Custom UserManager To Controller Net Core 2.1

我在尝试将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;
        }
    }

这是我的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();

其中两条重要的线是:
builder.RegisterType ApplicationUserManager()。作为UserManager ApplicationUser().SingleInstance();
builder.RegisterType ApplicationUserManager().As ApplicationUserManager().SingleInstance;



我的控制器:(我使用这2个构造函数对其进行了测试,但得到了相同的错误)

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

最后是错误:

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]])”。 在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参数)

提前致谢

如错误所述,您必须注册IUserStore和其他依赖项,这些依赖项通常是由AspNetIdentity的扩展方法注册的。

services.AddIdentity<ApplicationUser, IdentityRole>();

请注意,这也会添加cookie身份验证,因为这是asp.net身份所做的。 如果您坚持使用autofac这样做是完全合法的,则应在此处查看必须注册哪些类。

如果您想同时使用identity和jwt,那么这里是一个指导您完成它的好教程。

没有直接关系:

  • 请始终使用接口,不要注入实现,因此不要配置容器来解析实现。
  • 有一种新方法可以同时使用autofac和Microsoft的ioc。 您可以在此处找到示例。 这是asp.net core> = 2.0的通缉方法。

暂无
暂无

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

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