c# - AspIdentiy ApplicationUserManager 是静态的,如何扩展以使其参与我的 IoC 框架?

标签 c# asp.net asp.net-mvc mocking

在新的 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 中调用 ApplicationUserManager 上的创建:

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

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

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

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

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

如果我改变:

private My.Services.IEmailService _emailservice;

要public non-static我感觉IoC大神们摇头,我不能构建'需要对象引用'

最佳答案

今天我遇到了同样的问题(由于我是 Asp.Identity 的新手,所以仍在努力)。 我是这样做的:

  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>();
        }
    }
    
  2. 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"));
            }
        }
    }
    
  3. 控制者

    public class AccountController : Controller
    {
        private ApplicationUserManagerService _userManagerService;
        public AccountController(ApplicationUserManagerService userManagerService)
        {
            Contract.Requires(userManagerService != null);
            _userManagerService = userManagerService;
        }
        /*....*/
    }
    
  4. 应用程序用户

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

这对我有用,但请随时提出更好的解决方案。

关于c# - AspIdentiy ApplicationUserManager 是静态的,如何扩展以使其参与我的 IoC 框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23560952/

相关文章:

asp.net-mvc - 如何以编程方式记录 MVC FileResult 的开始和结束以记录不完整的下载?

c# - 通用 Func<T,K> 对不同类型的集合进行排序

c# - WinRT ListView 隐藏滚动条?

C# 手动删除对象指针

c# - Malwarebytes 为基本 C# "Hello World!"程序提供特洛伊木马警告

asp.net 图像上传控件(奖励 - 允许用户在保存之前裁剪图像)

c# - 如何在另一个文件更改时自动生成一个文件?

asp.net - MVC 3 AjaxHelper Ajax.ActionLink 与 Ajax.RouteLink,Ajax.BeginForm 与 A​​jaxBeginRouteForm

css - MVC、CSS 和 302 身份验证 hell

asp.net-mvc - Autofac 使用 Entity Framework 确定 MVC3 中工作单元的范围