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 ().As 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.IUserStore1[VotNetMon.Entities.ApplicationUser]、Microsoft.Extensions.Options.IOptions 1[Microsoft.AspNetCore.Identity.IdentityOptions], Microsoft.AspNetCore.Identity.IPasswordHasher1[VotNetMon.Entities.ApplicationUser]、System.Collections.Generic.IEnumerable 1[Microsoft.AspNetCore.Identity.IUserValidator1[VotNetMon.Entities.ApplicationUser]]、System.Collections.Generic.IEnumerable 1[Microsoft.AspNetCore.Identity.IPasswordValidator1[VotNetMon.Entities.ApplicationUser]]、Microsoft.AspNetCore.Identity.ILookupNormalizer、Microsoft.AspNetCore.Identity.IdentityErrorDescriber、System.IServiceProvider、Microsoft.Extensions.Logging.ILogger1[Microsoft.AspNetCore.Identity.UserManager1[VotNetMon.Entities.ApplicationUser]])'。在 Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext 上下文,IEnumerable 1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 参数)在 Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 参数)

提前致谢

4

1 回答 1

2

正如错误所说,您必须注册IUserStore通常由 AspNetIdentity 的扩展方法注册的其他依赖项。

services.AddIdentity<ApplicationUser, IdentityRole>();

请注意,这也会添加 cookie 身份验证,因为这是asp.net 身份所做的。如果你坚持用 autofac 做这件事,什么是完全合法的,你应该看看这里哪些类必须注册。

如果你想同时使用 identity 和 jwt,这里有一个很好的教程来指导你。

无直接关系:

  • 请始终使用接口,不要注入实现,因此不要配置容器来解析实现。
  • 有一种新方法可以同时使用 autofac 和 microsoft 的 ioc,这是首选。你可以在这里找到一个例子。这是 asp.net core >= 2.0 的通缉方式。
于 2018-08-01T08:44:45.430 回答