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

No IUserTokenProvider is registered when using dependency injection

调用 GeneratePasswordResetTokenAsync() 方法时出现错误。我用 owin 身份配置了 autofac。

错误是:

No IUserTokenProvider is registered when using dependency injection

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

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;
    }
}

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

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.csclass

中解析ApplicationUSerManager class
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>());

         }
     }

刚从here那里得到解决方案 这是一篇非常有帮助的文章