Home > Software engineering >  Console app Quarz.NET DI, can't create a job without an empty constructor
Console app Quarz.NET DI, can't create a job without an empty constructor

Time:11-21

I want to get a required object for my IJob from DI, so I have tried the following code but I get

Problem instantiating class 'test.MyJob: Cannot instantiate type which has no empty constructor (Parameter 'MyJob')'

Why doesn't it work?

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using System.Diagnostics;

namespace test
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureServices((_, services) =>
                {
                    services.AddTransient<MyJob>();
                    services.AddTransient<IDog, Dog>();
                    services.AddQuartz(q =>
                    {
                        q.ScheduleJob<MyJob>(trigger => trigger
                            .WithDailyTimeIntervalSchedule(x => x.WithInterval(10, IntervalUnit.Second))
                            );
                    });
                    services.AddQuartzHostedService();
                })
                .Build();
            await host.RunAsync();
        }
    }

    public interface IDog
    {
        string Name { get; }
    }

    public class Dog : IDog
    {
        public string Name => "Doge";
    }

    class MyJob : IJob
    {
        IDog _dog;
        public MyJob(IDog dog)
        {
            _dog= dog;
        }
        public Task Execute(IJobExecutionContext context)
        {
            Debug.WriteLine($"{_dog.Name} says {DateTime.Now}");
            return Task.CompletedTask;
        }
    }
}

If necessary, here is the project file

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
        <PackageReference Include="Quartz" Version="3.5.0" />
        <PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.5.0" />
        <PackageReference Include="Quartz.Extensions.Hosting" Version="3.5.0" />
    </ItemGroup>

</Project>

CodePudding user response:

I think that you are missing

 q.UseMicrosoftDependencyInjectionJobFactory();

in your services.AddQuartz block !?

Documentation

  • Related