当使用依赖注入时,没有注册IUserTokenProvider

本文关键字:注册 IUserTokenProvider 依赖 注入 | 更新日期: 2023-09-27 17:50:57

当我的GeneratePasswordResetTokenAsync()方法被调用时,我得到了一个错误。我用自己的身份配置了autoface。

错误是:

使用依赖注入时没有注册IUserTokenProvider

在我的sample.web项目中有一个AutofacConfig.cs文件,我在sample.repository项目中创建了signinmanagerusermanager

AutofacConfig.cs

public class AutofacConfig
{
    public static Autofac.IContainer RegisterDependencies()
    {
        var containerBuilder = new ContainerBuilder();
        // REGISTER DEPENDENCIES
        containerBuilder.RegisterType<SampleDataContext>()
                        .As<DbContext>()
                        .InstancePerDependency();
        containerBuilder.RegisterType<UserStore<SampleUser>>()
                        .As<IUserStore<SampleUser>>()
                        .InstancePerRequest();
        containerBuilder.RegisterType<ApplicationUserManager>()
                        .AsSelf()
                        .InstancePerRequest();
        containerBuilder.RegisterType<ApplicationSignInManager>()
                        .AsSelf()
                        .InstancePerRequest();
        containerBuilder.RegisterType<EmailService>();
        containerBuilder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication)
                        .InstancePerRequest();
        var container = containerBuilder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        var resolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
        return container;
    }
}

ApplicationUserManager.cs

public class ApplicationUserManager : UserManager<SampleUser>
{
     public ApplicationUserManager(IUserStore<SampleUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<SampleUser>(context.Get<SampleDataContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<SampleUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 8,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };
        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;
        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<SampleUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<SampleUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var provider = new DpapiDataProtectionProvider("Sample");
        manager.UserTokenProvider = new DataProtectorTokenProvider<SampleUser>(
        provider.Create("ASP.NET Identity"));
        return manager;
    }
}

当使用依赖注入时,没有注册IUserTokenProvider

删除ApplicationUserManager.cs类中的create()方法,并将该代码添加到ApplicationUserManager类的构造函数中。

ApplicationUserManager.cs

public class ApplicationUserManager : UserManager<SampleUser>
    {
        public ApplicationUserManager(IUserStore<SampleUser> store, IDataProtectionProvider dataProtectionProvider)
            : base(store)
        {
            // Configure validation logic for usernames
            this.UserValidator = new UserValidator<SampleUser>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // Configure validation logic for passwords
            this.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };
            // Configure user lockout defaults
            this.UserLockoutEnabledByDefault = true;
            this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            this.MaxFailedAccessAttemptsBeforeLockout = 5;
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<SampleUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<SampleUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            this.EmailService = new EmailService();
            this.SmsService = new SmsService();
           // var dataProtectionProvider = Startup.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
                this.UserTokenProvider = new DataProtectorTokenProvider<SampleUser>(dataProtector);
            }
        }

    }

在AutofacConfig.cs文件中注册DataProtectionProvider

containerBuilder.Register<IDataProtectionProvider>(c =>  Startup.DataProtectionProvider).InstancePerRequest();

在Startup.cs类中解析ApplicationUSerManager类

public partial class Startup
     {
        public static IDataProtectionProvider DataProtectionProvider { get; private set; }
        public void ConfigureAuth(IAppBuilder app)
        {
            // add this assignment
            DataProtectionProvider = app.GetDataProtectionProvider();
             // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(SampleDataContext.Create);
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
             app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationSignInManager>());
         }
     }

从这里得到了解这篇文章很有帮助