c# – AspIdentiy ApplicationUserManager是静态的,如何扩展,以便它参与我的IoC框架?

前端之家收集整理的这篇文章主要介绍了c# – AspIdentiy ApplicationUserManager是静态的,如何扩展,以便它参与我的IoC框架?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在一个新的ASPNET MVC应用程序中,您现在可以免费得到AspIdentity的好东西.

这里有一个无害的小线’插入你的电子邮件服务’.

所以我做了:

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在其中启动的那样,在Startup.Auth.cs中调用Create on ApplicationUserManager:

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

因为我正在使用AutoFac作为我的IoC容器,在global.asax.cs中

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

如果Create方法是静态的,我得到:
_emailService为空

我看过这里:http://forums.asp.net/post/5293670.aspxHow do i create an instance of UserManagerUsing Autofac to provide types exported by static factory.
但没有运气.

如果我改变:

private My.Services.IEmailService _emailservice;

被公开的非静态我感觉到IoC的神摇头,我不能建立“对象引用必需”

解决方法

今天我正在努力解决同样的问题(自从我刚开始接受Asp.Identity之后,我仍在努力工作).
我这样做:

> 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(我删除静态方法Create):

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,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> { }

这适用于我,但请随时提出更好的解决方案.

原文链接:https://www.f2er.com/csharp/94747.html

猜你在找的C#相关文章