找不到适合我使用 DI 的类型的构造函数

A suitable constructor for my type using DI could not be located

我有一个使用 Hangfire 进行后台作业的 .NET 核心 WebAPI 项目。我正在尝试为 DI 设置简单注入器。我的项目有一个 IFoo 和一个 Foo class,如下所示

public interface IFoo
{
    void DoSomething();
}

public class Foo : IFoo
{
    public Foo() { }
    public void DoSomething()
    {
        Console.WriteLine($"Foo::DoSomething");
    }
}

下面是我如何设置 Simple Injector 容器。我正在使用 Hangfire.SimpleInjector nuget 包

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        var container = new SimpleInjector.Container();
        container.Register<IFoo, Foo>();
        GlobalConfiguration.Configuration.UseActivator(
            new Hangfire.SimpleInjector.SimpleInjectorJobActivator(container));

        services.AddHangfire(x => x.UseSqlServerStorage(<My Connection string>));
        services.AddHangfireServer();
        services.AddControllers();
    }
}   

后台作业在控制器中设置如下

public IActionResult DoSomething()
{
    var jobID = BackgroundJob.Enqueue<IFoo>( x => x.DoSomething());

    return Ok();
}

但是此作业失败并出现以下堆栈跟踪。

An exception occurred during processing of a background job.

System.InvalidOperationException A suitable constructor for type 'MyWebAPI.Controllers.IFoo' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider, Type, Object[])
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider, Type)
at Hangfire.AspNetCore.AspNetCoreJobActivatorScope.Resolve(Type type)
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_0.<PerformJobWithFilters>b__0()
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter, PerformingContext, Func`1)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_1.<PerformJobWithFilters>b__2()
at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext, IEnumerable`1)
at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext, IStorageConnection, String)

我在设置这一切时做错了什么?

我不确定 Hangfire 中的 DI 是否用于此目的。

您需要依赖注入来解决内部依赖, 不要解析您要使用的主要类型。

您可以查看文档here

检查 this 相同问题的答案。