使用结构图依赖注入时,"没有注册IUserTokenProvider"

dip*_*ole 5 c# structuremap dependency-injection asp.net-mvc-5 asp.net-identity

我有一个MVC 5项目已被修改为使用int作为身份的主键,如本指南所示

然后我按照本指南中的说明启用了电子邮件确认

一切都按预期工作正常.然后我安装了structuremap.mvc5用于依赖注入,并添加了修改后的DefaultRegistry.cs

public DefaultRegistry() {
        Scan(
            scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.AssemblyContainingType(typeof(MyProject.Data.MyDbContext));
                scan.With(new ControllerConvention());
            });
        //For<IExample>().Use<Example>();
        For<IUserStore<ApplicationUser, int>>().Use<MyUserStore>().LifecycleIs<HttpContextLifecycle>();
        For<IAuthenticationManager>().Use(() => HttpContext.Current.GetOwinContext().Authentication);

    }
Run Code Online (Sandbox Code Playgroud)

该项目构建正常但在尝试在站点上注册新用户时,发送电子邮件确认现在抛出异常System.NotSupportedException:在调用UserManager.GenerateEmailConfirmationTokenAsync(userID)时没有注册IUserTokenProvider.

private async Task<string> SendEmailConfirmationTokenAsync(int userID, string subject)
    {
        string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
        var callbackUrl = Url.Action("ConfirmEmail", "Account",
           new { userId = userID, code = code }, protocol: Request.Url.Scheme);
        await UserManager.SendEmailAsync(userID, subject,
           "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

        return callbackUrl;
    }
Run Code Online (Sandbox Code Playgroud)

我是依赖注入的新手,很确定我做错了什么.我会感激你的想法和见解.

tra*_*max 7

IUserTokenProvider默认情况下,由OWIN插入,但是当您UserManager从DI容器中解析时,提供的组件IUserTokenProvider不可用,并且此组件未初始化.

您必须在可用时将令牌提供程序分配给全局静态变量,然后在UserManager构造函数中重用它:

public class AuthConfig
{
    public static IDataProtectionProvider DataProtectionProvider { get; set; }

    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();

        // do other configuration 
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在UserManager构造函数的构造函数中重新赋值:

public UserManager(/*your dependecies*/)
{
    var dataProtectorProvider = AuthConfig.DataProtectionProvider;
    var dataProtector = dataProtectorProvider.Create("My Asp.Net Identity");
    this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, Guid>(dataProtector)
    {
        TokenLifespan = TimeSpan.FromHours(24),
    };
    // other stuff
}
Run Code Online (Sandbox Code Playgroud)