.Net 6 中的 IServiceProvider 实例

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

在 Startup.cs 的 .Net 5 ASP.NET 应用程序中,我有以下内容(针对 Hangfire):

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
...
GlobalConfiguration.Configuration.UseActivator(new ServiceProviderJobActivator(serviceProvider));
...
}

我想转向 .Net 6 的配置方式(在 Program.cs 中),但我不知道如何获取 IServiceProvider 的实例以提供给 ServiceProviderJobActivator 方法。

方法是:

internal class ServiceProviderJobActivator : Hangfire.JobActivator
{
    private readonly IServiceProvider _serviceProvider;

    public ServiceProviderJobActivator(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public override object ActivateJob(Type type)
    {
        return _serviceProvider.GetService(type);
    }
}

我已经尝试过:

GlobalConfiguration.Configuration.UseActivator(new ServiceProviderJobActivator(app.Services));

我也尝试过:

    public override object ActivateJob(Type type)
    {
        return _serviceProvider.GetRequiredService(type);
    }

但是 ActivateJob 在这两种情况下都返回 null

谢谢

.net-6.0 hangfire service-provider
2个回答
3
投票

对于任何想了解如何获取

IServiceProvider
实例的人,在调用
builder.Build()
后,
app.Services
属性将解析为
IServiceProvider
实例。


0
投票

您是否尝试过将 .NET 5“基于启动”应用程序升级到 .NET 6 中的选项 3 之类的操作?

它应该导致类似的结果:

var app = builder.Build(); GlobalConfiguration.Configuration.UseActivator(new ServiceProviderJobActivator(app.Services));
    
© www.soinside.com 2019 - 2024. All rights reserved.