.NET 6 and Quartz.net how to use Dependency Injection for dbcontext?

82 views Asked by At

I am using Quartz.net version 3.7 and need to inject DbContext in the constructor. How would i do it ? Not able to find a good example using .net6.

public abstract class BaseJobMgr : IJob { private readonly PtmDBContext? _ctx;

    public Task Execute(IJobExecutionContext context)
    {

    }

}

1

There are 1 answers

0
keuleJ On

Use the nuget Quartz.Extensions.Hosting Then do something like this

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(...));
            });
}

See here