2

On my .Net 5 ASP.NET application at Startup.cs I have the follwing (for Hangfire):

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

I want to move to the .Net 6 way of configuration (in Program.cs), but I don't know how to get an instance of IServiceProvider to provide to the ServiceProviderJobActivator method.

The method is:

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

I have tried:

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

I also tried:

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

but the ActivateJob returns null in both cases

Thanks

ram dvash
  • 190
  • 1
  • 11

2 Answers2

3

For anyone looking how to get a IServiceProvider instance, after you call builder.Build() the app.Services property will resolve as an IServiceProvider instance.

Abel
  • 56,041
  • 24
  • 146
  • 247
  • 1
    I was looking for `app.ApplicationServices` (used in .NET 5), but as you stated that it's now `app.Services` (for .NET 6). Thanks for that! – mason81 Oct 29 '22 at 01:50
0

Have you tried something like option 3 from Upgrading a .NET 5 "Startup-based" app to .NET 6 ?

It should lead to something like :

var app = builder.Build();
GlobalConfiguration.Configuration.UseActivator(new ServiceProviderJobActivator(app.Services));
jbl
  • 15,179
  • 3
  • 34
  • 101