asp.net-mvc - 如何使用 StructureMap 配置 ASP.NET Identity ApplicationUserManager

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

我在我的项目中使用 asp.net 身份,并使用 Structuremap 作为 DI 框架。问题是当我使用构造函数注入(inject)时,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;
    }
}

我的问题是如何使用结构图配置我的 ApplicationUserManager ? 如果我将其设置为下面的代码,它可以工作,但我不知道它是否是一个好的解决方案:

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

请提示我是否有更好的解决方案,如果可以,那么它的最佳生命周期是多少? HttpContextScope,单例,...?

最佳答案

在为此创建 StructureMap 配置之前,了解如何手动创建它会有所帮助,即您是否实际上自己“新建”了所有内容。

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使用此配置,您可以在其中创建、列出和删除用户。

关于asp.net-mvc - 如何使用 StructureMap 配置 ASP.NET Identity ApplicationUserManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898428/

相关文章:

jQuery 日期选择器 : Prevent the "Today" button from being grayed out

.net - 使用.Net Entity Framework 删除具有子关系的实体问题

ASP.Net MVC 身份验证 - 基于角色隐藏 View 中的元素

c# - 来自类之间递归依赖的 System.StackOverflow 异常

Python依赖注入(inject)

c# - ASP.NET MVC + EF脚手架实现EntityTypeConfiguration类后可以使用吗?

c# - 带有元数据的 MEF GetExportedValue

asp.net-mvc - 使用 Fluent NHibernate 构建数据库表

asp.net-mvc - Structuremap 没有为此对象定义无参数构造函数

.net - 如何在代码中定义 Structuremap 命名实例