使用Simple Injector注册ApplicationUserManager

时间:2016-04-01 12:31:30

标签: c# asp.net-identity owin simple-injector

尝试运行项目时,如何修复以下错误。

  

ApplicationUserManager类型的构造函数包含参数   名称&#39; store&#39;并输入不是IUserStore<ApplicationUser>   注册。请确保IUserStore<ApplicationUser>已注册,   或者更改ApplicationUserManager的构造函数。

以下是我的身份配置

// Configure the user management application used in this application. 
// UserManager defined in ASP.NET Identity and is used in the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(
            new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Set the validation logic usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true,
        };

        // Set the password validation logic
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Set default values ​​for user lock
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Record authentication providers in two phases. 
        // This application uses the steps Phone & Email to receive a code
        // to check the user
        // You can write your own provider and connect here .
        manager.RegisterTwoFactorProvider("phone code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(
                    dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

以下是我的Account控制器及其相应的构造函数参数。我还删除了空构造函数,因为简单的注入器不支持多个构造函数,并且说是反模式。

public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;

    //public AccountController()
    //{
    //}

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set
        {
            _signInManager = value;
        }
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    //
    // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // No errors account login for the account lockout
        // To allow password errors trigger lock the account , switch to shouldLockout : true
        var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid username/password");
                return View(model);
        }
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                UserName = model.Email, Email = model.Email,
                Profile = new Profile
                {
                    EmployeeID = model.EmployeeID,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    MiddleName = model.MiddleName
                }
            };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information about enabling confirmation and account password reset , visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send email with this link
                // String code = await UserManager.GenerateEmailConfirmationTokenAsync ( user.Id ) ;
                // Var callbackUrl = Url.Action ( " Confirmemail " , "Account ", new { userId = user.Id , code = code} , protocol : Request.Url.Scheme ) ;
                // Await UserManager.SendEmailAsync ( user.Id , "Confirm Account" , " To confirm the account, click <a href=\"" + callbackUrl + "\"> here </a> ");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we reach this point , it is that it was an error and re- display the form
        return View(model);
    }

    private void AddErrors(IdentityResult result)
    {
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error);
        }
    }

    private ActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", "Home");
    }
}

下面是我的SimpleInjector配置

// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

// Register services
Config.RegisterContainer(container);

// This is an extension method from the integration package.
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

// This is an extension method from the integration package as well.
container.RegisterMvcIntegratedFilterProvider();

// This will register services
Config.RegisterContainer(container);

container.Verify();

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

0 个答案:

没有答案