使用ASP.NET Identity 2.2.1设置简单注入器

时间:2016-05-07 07:27:35

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

所以我一直在尝试设置ASP.NET Identity 2.2.1,并且我一直在遇到障碍。对于应该由框架自动生成的东西,配置肯定看起来很复杂。我想我差不多了,但我仍然遇到使用Simple Injector设置IoC的问题。

我一直在阅读有关这些问题的其他StackOverflow问题和博客。它们中的大多数似乎都已过时,因为它们处理的是ASP.NET Identity 1.0。甚至有足够的变化从2.0到2.2.1我遇到了一些过时解决方案的问题。或者解决方案处理其他IoC框架,我无法将它们转换为Simple Injector。我已经使用了其他IoC框架,但我是Simple Injector的新手。

更新 - Ric .Net's first link in his comment非常有帮助。我已经重新格式化我的工作以适应他的建议,我想我几乎就在那里。但我还有一个问题。我已经用下面的代码替换了以前的代码。

1)我更新了 ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(string connectionstring)
        : base(connectionstring, throwIfV1Schema: false)
    {
    }
}

2)我从 ApplicationUserManager 中删除了Create()方法,并将其移动到初始化所有Simple Injector代码的类中:

public static class SimpleInjectorInitializer
{
    public static Container Initialize(IAppBuilder app)
    {
        var container = GetInitializeContainer(app);

        container.Verify();

        DependencyResolver.SetResolver(
            new SimpleInjectorDependencyResolver(container));

        return container;
    }

    public static Container GetInitializeContainer(
              IAppBuilder app)
    {
        var container = new Container();

        container.RegisterSingle<IAppBuilder>(app);

        container.RegisterPerWebRequest<
               ApplicationUserManager>();

        container.RegisterPerWebRequest<ApplicationDbContext>(() 
          => new ApplicationDbContext(
           "Your constring goes here"));

        container.RegisterPerWebRequest<IUserStore<
          ApplicationUser>>(() => 
            new UserStore<ApplicationUser>(
              container.GetInstance<ApplicationDbContext>()));

        container.RegisterInitializer<ApplicationUserManager>(
            manager => InitializeUserManager(manager, app));

        container.RegisterMvcControllers(
                Assembly.GetExecutingAssembly());

        return container;
    }

    private static void InitializeUserManager(
        ApplicationUserManager manager, IAppBuilder app)
    {
        manager.UserValidator = 
         new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        //Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator()
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        var dataProtectionProvider = 
             app.GetDataProtectionProvider();

        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
             new DataProtectorTokenProvider<ApplicationUser>(
              dataProtectionProvider.Create("ASP.NET Identity"));
        }
    }
}

3)我更改了 Startup.cs 中的配置方法:

public void Configuration(IAppBuilder app)
{
    var container = SimpleInjectorInitializer.Initialize(app);
    ConfigureAuth(app, container);
}

4)我在 Configure.Auth.cs 中更新了ConfigureAuth:

public void ConfigureAuth(IAppBuilder app, Container container)
{
    // Configure the db context and user manager to use a single instance per request
    //app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext(container.GetInstance<ApplicationUserManager>);
    // Rest of code here ...

5)然后我从AccountsController中删除了默认构造函数和UserManager属性。

我现在遇到的问题是,自ASP.NET Identity 2.0以来,他们已将参数ISecureDataFormat<AuthenticationTicket> accessTokenFormat添加到AccountsController构造函数中。

public AccountController(ApplicationUserManager userManager, 
    ISecureDataFormat<AuthenticationTicket> accessTokenFormat)

现在,如何在Simple Injector中为ISecureDataFormat<AuthenticationTicket>添加DI?

1 个答案:

答案 0 :(得分:4)

所以在帮助Ric .Net(我在上面作为问题的一部分发布)和Lucas Teles answer in another question之间,我终于得到了答案。 Lucas建议将这些行添加到我的Simple Injector设置中:

container.Register<ISecureDataFormat<AuthenticationTicket>,
    SecureDataFormat<AuthenticationTicket>>(Lifestyle.Scoped);
container.Register<ITextEncoder, Base64UrlTextEncoder>(Lifestyle.Scoped);
container.Register<IDataSerializer<AuthenticationTicket>, TicketSerializer>(
    Lifestyle.Scoped);
container.Register<IDataProtector>(
    () => new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider()
        .Create("ASP.NET Identity"),
    Lifestyle.Scoped);

所以现在我的容器构建方法如下所示:

public static Container GetInitializeContainer(IAppBuilder app)
{
    var container = new Container();

    // IoC for ASP.NET Identity
    container.RegisterSingleton<IAppBuilder>(app);
    container.Register<ApplicationUserManager>(Lifestyle.Scoped);
    container.Register<ApplicationDbContext>(
        () => new ApplicationDbContext("Your constring goes here"),
        Lifestyle.Scoped);
    container.Register<IUserStore<ApplicationUser>>(
        () => new UserStore<ApplicationUser>(
            container.GetInstance<ApplicationDbContext>()),
        Lifestyle.Scoped);
    container.RegisterInitializer<ApplicationUserManager>(
        manager => InitializeUserManager(manager, app));
    // Setup for ISecureDataFormat
    container.Register<ISecureDataFormat<AuthenticationTicket>, 
        SecureDataFormat<AuthenticationTicket>>(Lifestyle.Scoped);
    container.Register<ITextEncoder, Base64UrlTextEncoder>(Lifestyle.Scoped);
    container.Register<IDataSerializer<AuthenticationTicket>, 
        TicketSerializer>(Lifestyle.Scoped);
    container.Register<IDataProtector>(
        () => new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider()
            .Create("ASP.NET Identity"),
        Lifestyle.Scoped);

    // Register all controllers
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    return container;
}