简体   繁体   English

从Hangfire Job获取UserManager

[英]Get UserManager from Hangfire Job

I am using Hangfire to run background jobs, as part of one of those jobs I want to be able to send emails. 我正在使用Hangfire来运行后台作业,作为我希望能够发送电子邮件的其中一项工作的一部分。 I would like to use the mechanism I have in the rest of my application namely using UserManager.SendMailAsync. 我想在我的应用程序的其余部分使用我的机制,即使用UserManager.SendMailAsync。 The difficulty I have is being able to create a reference to the OwinContext or UserManager inside a hangfire tasks. 我遇到的困难是能够在hangfire任务中创建对OwinContext或UserManager的引用。

Code like: 代码如:

HttpContext.Current.GetOwinContext()

Will just fail with an error. 只会因错误而失败。 As per the hangfire documentation I have create an authorization filter which can successfully attach to the OwinContext, however I cannot seem to be find a way to do this inside a hangfire task. 根据hangfire文档,我创建了一个可以成功附加到OwinContext的授权过滤器,但是我似乎找不到在hangfire任务中执行此操作的方法。

I've also tried the following: 我也尝试过以下方法:

 var context = new OwinContext();
            var aaa = context.GetUserManager<ApplicationUserManager>();

I can never get a reference to the user manager 我永远无法获得对用户管理器的引用

var userManager = new ApplicationUserManager(
    new UserStore<ApplicationUser>(new ApplicationDbContext()));

Then do what you want on this userManager . 然后在此userManager上执行您想要的userManager

NOTE 注意

Be Careful when use this trick, you must make sure your code won't take different UserManager instance to update(user). 使用此技巧时要小心,您必须确保您的代码不会使用不同的UserManager实例进行更新(用户)。 for example: 例如:

/* Wrong demonstration */

var userManagerA = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var userFormA = userManagerA.FindByName(User.Identity.Name);
userFormA.EmailConfirmed = false;
// some stuff ...

var userManagerB = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
// Will product a Exception from EntityFramework
userManagerB.Update(userFormA);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM