I’m currently trying to migrate an existing project to .Net Core 7 – which uses Autofac and Hangfire.
The problem I’m faced with is not only the completely different configuration required, especially since I’m migrating from ASP.NET MVC, it’s setting up Autofac and Hangfire to work together, and wherever I look, I keep getting different solutions – none of which have worked.
Program.cs looks like the following:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
// register own types here
builder.RegisterType<CommandDispatcher>().As<ICommand>();
});
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
// add hangfire
builder.Services.AddHangfire(config => config
.UseRecommendedSerializerSettings()
.UseAutofacActivator() /* where / how do I get an instance of ILifetimeScope */
.UseSqlServerStorage(builder.Configuration.GetConnectionString("TempHangfireDb"), new SqlServerStorageOptions { SchemaName = "SiteOne" }));
// add hangfire processor
builder.Services.AddHangfireServer();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
How do I get hold of a reference to ILifetimeScope that can be used in the call to
.UseAutofacActivator()
above?
I know Autofac isn’t being registered correctly with Hangfire because when the following
BackgroundJob.Enqueue<CommandDispatcher>(t => t.Execute(commandArgs));
is called, it results in an exception – No Parameterless Constructor Defined.
It is very frustrating that the code from Hangfire and Autofac is very much ready but the documentation on both is severely limited and is far from current.