How to configure ASP.NET Identity ApplicationUserManager with StructureMap

前端 未结 1 1829
名媛妹妹
名媛妹妹 2021-01-02 06:37

I am using asp.net identity in my project and using structuremap as DI framework. the problem is when i use constructor injection then ApplicationUserManager not configured

相关标签:
1条回答
  • 2021-01-02 07:03

    Before you create the StructureMap configuration for this, it helps to know how you would create it manually, i.e., if you actually "new up" everything yourself.

    UserManager has a dependency on IUserStore, and its EntityFramework implementation (UserStore) has a dependency on DbContext. Doing everything manually would look like this:

    var dbContext = new IdentityDbContext("Your ConnectionString Name");
    var userStore = new UserStore<IdentityUser>(dbContext);
    var userManager = new UserManager<IdentityUser>(userStore);
    

    (Replace IdentityUser with your custom user, if you are using one)

    You can then configure UserManager like this:

    userManager.PasswordValidator = new PasswordValidator
    {
        RequiredLength = 6
    };
    

    The most complicated part about configuring userManager is related to the UserTokenProvider (that uses the data protection api), if you would do it manually it would look like this:

    var dataProtectionProvider = new DpapiDataProtectionProvider("Application name");
    var dataProtector = dataProtectionProvider.Create("Purpose");
    userManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(dataProtector);
    

    Here's an example of a StructureMap registry (you can extrapolate from this example and adapt it to your own needs):

     public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.With(new ControllerConvention());
                });
    
    
            For<IUserStore<IdentityUser>>()
                .Use<UserStore<IdentityUser>>()
                .Ctor<DbContext>()
                .Is<IdentityDbContext>(cfg => cfg.SelectConstructor(() => new IdentityDbContext("connection string")).Ctor<string>().Is("IdentitySetupWithStructureMap"));
    
            ForConcreteType<UserManager<IdentityUser>>()
                .Configure
                .SetProperty(userManager => userManager.PasswordValidator = new PasswordValidator
                {
                    RequiredLength = 6
                })
                .SetProperty(userManager => userManager.UserValidator = new UserValidator<IdentityUser>(userManager));                
        } 
    

    I wrote a blog post about this, it explains the process that lead to this configuration, there's also a link to an example on github of an MVC project where, using this configuration, you can create, list and delete users.

    0 讨论(0)
提交回复
热议问题