本文介绍了AspIdentiy ApplicationUserManager是静态的,如何扩展,因此参与我的IoC框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新的ASPNET MVC应用程序你现在得到AspIdentity东西是免费的。

In a new ASPNET MVC application you now get the AspIdentity goodies for free.

有一个无伤大雅的小线在您的电子邮件服务在这里插件。

There's a harmless little line 'plug in your email service here'.

所以,我所做的:

public class EmailService : IIdentityMessageService
{
    private static My.Services.IEmailService _emailservice;

    public EmailService(Insolvency.Services.IEmailService emailservice)
    {
        _emailservice = emailservice;
    }

    public Task SendAsync(IdentityMessage message)
    {
        _emailservice.SendEmail(message);
       return Task.FromResult(0);
    }
}

和现在的喜悦:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    private My.Services.IEmailService _emailservice;

    public ApplicationUserManager(IUserStore<ApplicationUser> store, My.Services.IEmailService emailservice): base(store)        
    {
        _emailservice = emailservice;
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()), _emailservice);
       ...

在它Owin踢会调用在ApplicationUserManager创建 Startup.Auth.cs

public partial class Startup 
   {
    public void ConfigureAuth(IAppBuilder app) 
     {
        ...
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

和我敢用AutoFac作为我IoC容器中的global.asax.cs

and as I'm using AutoFac as my IoC container, in global.asax.cs

builder.RegisterType<My.Services.EmailService>().As<IEmailService>();

如果创建方法是静态的,所以我得到:结果
_emailService 为空

if the Create method is static so I get:
_emailService is null

我在这里看:和How做我创建的UserManager的和Using Autofac提供由静态工厂出口类型。
但没有运气。

I've looked here:http://forums.asp.net/post/5293670.aspx, and How do i create an instance of UserManager and Using Autofac to provide types exported by static factory.but no luck.

如果我更改:

private My.Services.IEmailService _emailservice;

是公共的非静态,​​我觉得国际奥委会神摇头,我不能建设所需的对象引用

to be public non-static I feel IoC gods shaking their heads, and I can't build 'object reference required'

推荐答案

今天,我用同样的问题(它仍然在工作,因为我是新来的Asp.Identity)挣扎。
我就是这么做的:

Today I was struggling with the same issue (still working on it since I'm new to Asp.Identity).I did it this way:


  1. Startup.cs(使用自己的容器)

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var authConfigurator = new AuthConfigurator();
        authConfigurator.ConfigureAuth(app);
        var unityContainer = UnityConfig<MvcUnityDependencyContainer>.UseContainer();
        //Asp identity registration
        IDataProtectionProvider dataProtectionProvider = app.GetDataProtectionProvider();
        unityContainer.RegisterInstance(dataProtectionProvider);
        unityContainer.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
        unityContainer.RegisterType<UserManager<ApplicationUser, int>>(new HierarchicalLifetimeManager());
        unityContainer.RegisterType IIdentityMessageService, EmailService>();
        unityContainer.RegisterType<IUserStore<ApplicationUser, int>,
            UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>>(
            new InjectionConstructor(new ApplicationDbContext()));
        unityContainer.RegisterType<IIdentityMessageService, EmailService>();
    }
}


  • ApplicationUserManager(我删除静态方法创建):

    public class ApplicationUserManagerService : UserManager<ApplicationUser, int>
    {
        public ApplicationUserManagerService(IUserStore<ApplicationUser, int> store, 
                                             IIdentityMessageService emailService,
                                             IDataProtectionProvider dataProtectionProvider)
                                             : base(store)
        {
            UserTokenProvider = new EmailTokenProvider<ApplicationUser, int>();
            EmailService = emailService;
            Configure(dataProtectionProvider);
        }
        private void Configure(IDataProtectionProvider dataProtectionProvider)
        {
            // Configure validation logic for usernames
            UserValidator = new UserValidator<ApplicationUser, int>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // Configure validation logic for passwords
            PasswordValidator = new PasswordValidator
            {
                RequiredLength = 1,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };
            // 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 in here.
            RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser, int>
            {
                MessageFormat = "Your security code is: {0}"
            });
            RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser, int>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is: {0}"
            });
            if (dataProtectionProvider != null)
            {
                UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
        }
    }
    


  • 控制器

    public class AccountController : Controller
    {
        private ApplicationUserManagerService _userManagerService;
        public AccountController(ApplicationUserManagerService userManagerService)
        {
            Contract.Requires(userManagerService != null);
            _userManagerService = userManagerService;
        }
        /*....*/
    }
    


  • ApplicationUser

    public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }
    }
    
    public class CustomRole : IdentityRole<int, CustomUserRole>
    {
        public CustomRole() { }
        public CustomRole(string name) { Name = name; }
    }
    
    public class CustomUserClaim : IdentityUserClaim<int> { }
    public class CustomUserLogin : IdentityUserLogin<int> { }
    public class CustomUserRole : IdentityUserRole<int> { }
    


  • 这对我的作品,但请随时提出更好的解决方案。

    This works for me but please feel free to suggest better solution.

    这篇关于AspIdentiy ApplicationUserManager是静态的,如何扩展,因此参与我的IoC框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    10-30 06:21