【问题标题】:Binding a ASP.Net Identity object to a Func using ninject使用 ninject 将 ASP.Net Identity 对象绑定到 Func
【发布时间】:2015-02-10 11:03:15
【问题描述】:

编辑:我找到了解决方案,但如果有人知道更好的方法,我会全力以赴。

我正在开发一个带有一些 ASP.Net Identity 的 ASP.Net MVC 5 应用程序。

我有以下代码(在应用启动时在 Startup.cs 中运行):

 public class Startup
{

    #region Properties/Delegates

    public static Func<UserManager<AppUserModel>> UserManagerFactory { get; private set; }

    #endregion


    public void Configuration(IAppBuilder app)
    {



        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/auth/login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<AppUserModel>, AppUserModel>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });


        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


        // Configure the user manager
        // We use a delegate here so we can acess the IBuilder
        // Then we bind this delegate to UserManager<AppUserModel> in Ninject
        UserManagerFactory = () =>
        {
            var usermanager = new UserManager<AppUserModel>(
                new UserStore<AppUserModel>(new AppDbContext()));

            usermanager.PasswordHasher = new SQLPasswordHasher();

            // allow alphanumeric characters in username
            usermanager.UserValidator = new UserValidator<AppUserModel>(usermanager)
            {
                AllowOnlyAlphanumericUserNames = false
            };

            usermanager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false
            };

            usermanager.UserLockoutEnabledByDefault = true;
            usermanager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            usermanager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            usermanager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<AppUserModel>
            {
                MessageFormat = "Your security code is {0}"
            });
            usermanager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<AppUserModel>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            usermanager.EmailService = new EmailService();
            usermanager.SmsService = new SmsService();

            IDataProtectionProvider provider = app.GetDataProtectionProvider();
            if (provider != null)
            {
                IDataProtector dataProtector = provider.Create("ASP.NET Identity");

                usermanager.UserTokenProvider = new DataProtectorTokenProvider<AppUserModel>(dataProtector);
            }


            // use out custom claims provider
            //usermanager.ClaimsIdentityFactory = new AppUserClaimsIdentityFactory();

            return usermanager;
        };

    }

我想注入上面的 UserManagerFactory 来代替 UserManager。 我似乎无法让绑定工作。

我尝试过的:

kernel.Bind<UserManager<AppUserModel>>().To<Startup.UserManagerFactory>();

实际效果:

kernel.Bind<UserManager<AppUserModel>>().ToMethod(context => Startup.UserManagerFactory());

UserManager 是 Microsoft Identity 拥有的对象。

我想将 Delegate 注入到这样的东西中:

private readonly UserManager<AppUserModel> _userManager;

    public AuthController(UserManager<AppUserModel> userManager)
    {
        this._userManager = userManager;
    }

这是基于http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-2

在配置 UserManager 和身份验证下。他将它调用到我选择 ninject 的构造函数中。

【问题讨论】:

  • 两件事:1)构造函数注入应该总是优于属性注入,2)由于UserManagerFactory属性是具体类型(非抽象),为什么根本需要注入对于静态函数?上面代码中的内核绑定默认值将是InTransientScope(Ninject 默认值),因此将在每个引用上创建一个新实例,但由于该函数是静态的,这实际上不会发生。您能否提供更多有关此代码在何处/如何使用的上下文?
  • 在帖子中添加了详细信息。请查看。

标签: c# asp.net-mvc-5 ninject asp.net-identity-2 ninject.web.mvc


【解决方案1】:

解决了

kernel.Bind<UserManager<AppUserModel>>().ToMethod(context => Startup.UserManagerFactory());

如果有更好的方法,请告诉我!

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多