ASP.Net 6.0 上有一个站点。在 Configure startyp.cs 中创建了一个初始化类
public static class SiteInit
{
private static void AddTasks (IServiceProvider serviceProvider, [NotNull] IConfiguration configuration)
{
//Получаю DependencyIjector
serviceProvider = serviceProvider.CreateScope().ServiceProvider;
//Провожу инъекцию аккаунта
AccountManager account = serviceProvider.GetRequiredService<AccountManager>();
byte.TryParse(configuration["accountsettings:newbieexceededhours"], out byte hourstodelete);
/* To-Do после теста отключить на Dayly */
RecurringJob.AddOrUpdate(() => NewbieDeleterTask.Execute(account, hourstodelete), Cron.Hourly);
}
public static void InitSite (IServiceProvider service,[NotNull] IConfiguration configuration)
{
AddTasks(service, configuration);
}
}
它的任务是初始化类中给出的任务:
/// <summary>
/// Задача удаления новичков после n часов
/// </summary>
public static class NewbieDeleterTask
{
private static async Task ExecuteAsync ([NotNull] AccountManager account, byte hours = 36)
{
//Получение текущей даты
DateTime dateTime = DateTime.UtcNow;
//Получение списока пользователей с неподтверждённым email
IEnumerable<MyUser> notConfirmedUsers = account.GetAllUsers().Where(usr => !usr.EmailConfirmed);
//Список "просроченных" пользователей
// ReSharper disable once CollectionNeverQueried.Local
List<MyUser> overdueUsers = new();
//Получаем список просрочек
foreach (MyUser user in notConfirmedUsers)
{
if (await account.IsUserInRoleAsync(user, "newbie") && user.DateOfRegister.AddHours(hours).CompareTo(dateTime) <= 0)
overdueUsers.Add(user);
}
//Удаляем пользователей
foreach (MyUser user in overdueUsers)
await account.DeleteUserAsync(user);
}
public static void Execute([NotNull] AccountManager account, byte hours = 36) =>
ExecuteAsync(account, hours).GetAwaiter().GetResult();
}
AccountManager 本身是 usermanager 和 rolemanager 类的包装器。
一般来说,Hangfire 是这样发誓的:
warn: Hangfire.AutomaticRetryAttribute[0]
Failed to process the job '10004': an exception occurred. Retry attempt 1 of 10 will be performed in 00:00:21.
System.NullReferenceException: Object reference not set to an instance of an object.
at rnrmm.Platform.AccountManager.GetAllUsers() in E:\WebSites\rnrmm_ru\rnrmm_ru\Platform\AccountManager.cs:line 69
at rnrmm.Tasks.NewbieDeleterTask.ExecuteAsync(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 25
at rnrmm.Tasks.NewbieDeleterTask.Execute(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 44
warn: Hangfire.AutomaticRetryAttribute[0]
Failed to process the job '10004': an exception occurred. Retry attempt 2 of 10 will be performed in 00:00:24.
System.NullReferenceException: Object reference not set to an instance of an object.
at rnrmm.Platform.AccountManager.GetAllUsers() in E:\WebSites\rnrmm_ru\rnrmm_ru\Platform\AccountManager.cs:line 69
at rnrmm.Tasks.NewbieDeleterTask.ExecuteAsync(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 25
at rnrmm.Tasks.NewbieDeleterTask.Execute(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 44
GetAllUsers函数本身如下所示:
public List<MyUser> GetAllUsers ()
{
IQueryable<MyUser> usersQuery = usermanager.Users;
return usersQuery.ToList();
}
怎么了?为什么她没有获得用户(网站上有 3 个用户)!
问题简单解决:需要将静态类 NewbieDeleterTask 转为正常注入的服务,添加到startup中:
然后在正确的地方创建一个任务: