Home > OS >  DI Chaining with .NET 6 Generic Host
DI Chaining with .NET 6 Generic Host

Time:08-20

I am trying to write a Windows service in .NET 6 (first attempt). I have been able to set up the project just fine, but am running into issues when I attempt to chain dependencies. So my constructors would be setup something like this (Worker added as HostedService, others as Singleton):

public class Settings
{
    public Settings(){}
}
public class Class1
{
    private readonly ILogger<Class1> _Logger;
    private readonly Settings _Settings;

    public Class1(ILogger<Class1> logger, Settings settings)
    {
        _Logger = logger;
        _Settings = settings;
    }
}
public class Class2
{
    private readonly ILogger<Class2> _Logger;
    private readonly Settings _Settings;

    public Class2(ILogger<Class2> logger, Settings settings)
    {
        _Logger = logger;
        _Settings = settings;
    }
}
public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _Logger;
    private readonly Settings _Settings;
    private readonly Class1 _Class1;
    private readonly Class2 _Class2;

    public Worker(ILogger<Worker> logger, Settings settings, Class1 class1, Class2 class2)
    {
        _Logger = logger;
        _Settings = settings;
        _Class1 = class1;
        _Class2 = class2;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _Logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}
var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>()
            .AddSingleton<Settings>()
            .AddSingleton<Class1>()
            .AddSingleton<Class2>()
    })
    .Build();

await host.RunAsync();

Now, when it tries to resolve the dependencies, I get the following error message:

Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: DI.Worker': A suitable constructor for type 'DI.Class1' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

I went and tried to follow the steps listed in the documentation and I get the same error. I assume I am missing something but I cannot figure out what.

CodePudding user response:

In my actual application, I wasn't using interfaces for all of my services, instead adding them concrete. As for the sample from the documentation, the classes were internal instead of public.

CodePudding user response:

I think that the order matters.

Try this:

     services.
        .AddSingleton<Settings>()
        .AddSingleton<Class1>()
        .AddSingleton<Class2>()
        .AddHostedService<Worker>();

If that is not it, then maybe Logging is not being setup. It should be because you are using CreateDefaultBuilder, but that would be my next try.

If this does not solve it, can you provide the full program.cs and startup.cs files?

  • Related