将自定义UserManager注入Controller Net Core 2.1

时间:2018-08-01 07:55:31

标签: asp.net asp.net-core code-injection usermanager

我在尝试将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:没有构造函数   发现与   类型上的“ Autofac.Core.Activators.Reflection.DefaultConstructorFinder”   'VotNetMon.ApplicationUserManager'可以通过可用的调用   服务和参数:无法解析参数   '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,   System.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   参数)

预先感谢

1 个答案:

答案 0 :(得分:1)

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

services.AddIdentity<ApplicationUser, IdentityRole>();

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

如果您想同时使用身份和jwt,here是一个很好的教程,可以指导您完成操作。

不直接相关:

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