如何使用StructureMap配置ASP.NET标识ApplicationUserManager

时间:2014-09-17 19:06:01

标签: asp.net-mvc dependency-injection structuremap asp.net-identity asp.net-identity-2

我在我的项目中使用asp.net身份并使用structuremap作为DI框架。问题是当我使用构造函数注入时,然后ApplicationUserManager没有配置所有它的成员,例如TokenProvider,...

这是我的ApplicationUserManager类:

public class ApplicationUserManager : UserManager<User, long>
{
    public ApplicationUserManager(IUserStore<User, long> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new CustomUserStore(context.Get<InsuranceManagementContext>()));

        // Configure the application user manager
        manager.UserValidator = new UserValidator<User, long>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = false
        };

        manager.PasswordValidator = new PasswordValidator
        {
            RequireDigit = true,
            RequiredLength = 8,
            RequireLowercase = false,
            RequireNonLetterOrDigit = true,
            RequireUppercase = false
        };

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<User, long>(dataProtectionProvider.Create("TEST"));
        }

        return manager;
    }
}

这是Startup.Auth类:

public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(InsuranceManagementContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            ExpireTimeSpan = TimeSpan.FromHours(2.0),
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
        });
    }
}

及其我的AccountController:

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

    public AccountController(ApplicationUserManager userManager)
    {
        UserManager = userManager;
    }
}

我的问题是我如何使用structuremap配置我的ApplicationUserManager? 如果我把它设置为下面的代码它可以工作,但我不知道这是一个很好的解决方案:

ObjectFactory.Initialize(x =>
{
     ...
     x.For<ApplicationUserManager>().Use(() => HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>());
     ...
});

请提示我,如果有更好的解决方案,如果可以,那么它的最佳寿命是多少? HttpContextScope,Singleton,......?

1 个答案:

答案 0 :(得分:6)

在为此创建StructureMap配置之前,有助于了解如何手动创建它,即,如果您实际上是&#34; new up&#34;一切都在你自己。

UserManager依赖于IUserStore,其EntityFramework实现(UserStore)依赖于DbContext。 手动完成所有操作将如下所示:

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

(将IdentityUser替换为您的自定义用户(如果您使用的话)

然后,您可以像这样配置UserManager

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

关于配置userManager最复杂的部分与UserTokenProvider(使用数据保护api)有关,如果您手动执行,它将look like this

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

这是一个StructureMap注册表的示例(您可以从此示例中进行推断并根据自己的需要进行调整):

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

我写了一篇博客post about this,它解释了导致此配置的过程,还有link to an example on github of an MVC project,使用此配置,您可以创建,列出和删除用户。