.NET 6 和 Quartz.net 如何对 dbcontext 使用依赖注入?

问题描述 投票:0回答:1

我使用的是 Quartz.net 3.7 版本,需要在构造函数中注入 DbContext。我该怎么做呢?找不到使用 .net6 的好例子。

公共抽象类 BaseJobMgr : IJob { 私有只读 PtmDBContext? _ctx;

    public Task Execute(IJobExecutionContext context)
    {

    }

}

dependency-injection .net-6.0 dbcontext quartz.net
1个回答
0
投票

使用 nuget

Quartz.Extensions.Hosting
然后做这样的事情

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                // Add the required Quartz.NET services
                services.AddQuartz(q =>  
                {
                    // Use a Scoped container to create jobs. 
                    // Like this you should be able to use DBContext
                    q.UseMicrosoftDependencyInjectionScopedJobFactory();
                });

                // Add the Quartz.NET hosted service
                services.AddQuartzHostedService(
                    q => q.WaitForJobsToComplete = true);

                // config for EF Core
                services.AddDbContext<IMyDbContext, MyDbContext>(options =>
                    options.UseSqlServer(...));
            });
}

参见这里

© www.soinside.com 2019 - 2024. All rights reserved.