gpt4 book ai didi

asp.net-mvc - 使用 ApplicationDBContext 的后台线程

转载 作者:行者123 更新时间:2023-12-03 12:59:02 26 4
gpt4 key购买 nike

我正在尝试连接一个后台线程,该线程将每小时从 Active Directory 更新一次数据库。我不确定如何通过当前

    public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Connection")));

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
services.AddSession();
services.AddHttpContextAccessor();

services.AddSingleton(Configuration);
services.AddScoped<IAppDbRepository, AppDbRepository>();
services.AddScoped<IActiveDirectoryUtility, ActiveDirectoryUtility>();
services.AddScoped<IActiveDirectoryManager, ActiveDirectoryManager>();

services.AddHostedService<LdapManager>();
services.AddScoped<ILdapManager, LdapManager>();

}

In the LdapManager class I would like to call the UpdateUsers method every hour:

public class LdapManager : ILdapManager, IHostedService
{
private IConfiguration _configuration = null;
private Logging _logger;
private List<string> ldapConnectorForDirectoryEntries = new List<string>();

public LdapManager(IConfiguration configuration)
{
_configuration = configuration;

UpdateUsers();
SyncActiveDirectoryUsers();
}


public void SyncActiveDirectoryUsers()
{
try
{
using (var waitHandle = new AutoResetEvent(false))
{
ThreadPool.RegisterWaitForSingleObject(waitHandle, (state, timeout) => { UpdateUsers(); }, null, TimeSpan.FromHours(1), false);
}
}
catch
{
throw;
}
}
}

UpdateUsers() 方法应该能够调用 applicationDBContext.SaveChanges() 方法。

如何确保 LDAP 管理器类可以使用 Application DB 上下文?

最佳答案

你可能想要 class LdapManager : BackgroundService, ILdapManager
BackgroundService 是 .NET Core 2.1,有一个可用于 core 2.0 的代码示例

注入(inject) IServiceScopeFactory并覆盖 Task ExecuteAsync( ) ,在那里运行一个while循环。

while(!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
...; // do your stuff
}
await Task.Delay(myConfig.BackgroundDelay, stoppingToken);
}

这是一个很好的 read about this on MSDN ,包括 2.0 的代码示例

关于asp.net-mvc - 使用 ApplicationDBContext 的后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53453235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com