如何配置ASP.NET身份ApplicationUserManager与StructureMap [英] How to configure ASP.NET Identity ApplicationUserManager with StructureMap

查看:538
本文介绍了如何配置ASP.NET身份ApplicationUserManager与StructureMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 all of it's members e.g TokenProvider, ...

这是我的ApplicationUserManager类:

this is my ApplicationUserManager class:

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类:

this is Startup.Auth class:

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:

and its my 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?
如果我将其设置为低于code它的工作原理,但我不知道这是一个很好的解决方案或不:

my question is how can i configure my ApplicationUserManager with structuremap? if i set it as the below code it works but i don't know it is a good solution or not:

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

请暗示我,如果有一个更好的解决方案,如果它是确定的又是什么它最好的寿命是多少? HttpContextScope,辛格尔顿,...?

please hint me if there is a better solution and if it is ok then what is the best lifetime for it? HttpContextScope, Singleton, ...?

推荐答案

在创建这个StructureMap配置之前,它有助于了解你将如何手动创建,也就是说,如果你实际上是新达一切自己。

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对IUserStore的依赖,它的EntityFramework实现(UserStore)对的DbContext的依赖。
手工做的一切是这样的:

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

(替换 IdentityUser 与自定义的用户,如果您正在使用)

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

您可以再配置的UserManager 是这样的:

You can then configure UserManager like this:

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

有关配置的UserManager是关系到UserTokenProvider(即使用数据保护API),如果你想手工做的那样的这个样子

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

下面是一个StructureMap登记的例子(你可以从这个例子推断并使之适应自己的需要):

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

我写了一篇博客后这个,它解释说,导致这种配置的过程中,也有一个链接的例子在一个MVC的github上项目在哪里,使用此配置,您可以创建,列表和删除用户。

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.

这篇关于如何配置ASP.NET身份ApplicationUserManager与StructureMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆