I have a structured project with DDD layers, where Hangfire is used to send asynchronous emails. At the service call point, the following error is generated:
System.InvalidOperationException HResult=0x80131509 Message=The request lifetime scope cannot be created because the HttpContext is not available. Source=Autofac.Integration.Mvc StackTrace: at Autofac.Integration.Mvc.RequestLifetimeScopeProvider.GetLifetimeScope(Action`1 configurationAction) at Autofac.Integration.Mvc.AutofacDependencyResolver.get_RequestLifetimeScope() at Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType) at System.Web.Mvc.DependencyResolverExtensions.GetService[TService](IDependencyResolver resolver) at Track.Web.Job.DoWork() in I:...\Jobs\Job.cs:line 19
How resolve it ?
This is my Source :
// Startup.cs
[assembly: OwinStartup(typeof(MyWeb.Startup))]
namespace MyWeb
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configuration.UseSqlServerStorage(
"MyEntities",
new SqlServerStorageOptions
{
PrepareSchemaIfNecessary = false,
QueuePollInterval = TimeSpan.FromSeconds(1)
}).UseFilter(new LogFailureAttribute());
BackgroundJob.Enqueue(() => Console.WriteLine("Getting Started with HangFire!"));
RecurringJob.AddOrUpdate(() => new Job().DoWork(), Cron.Minutely);
app.UseHangfireDashboard();
app.UseHangfireServer();
}
}
}
// Bootstrapper.cs
namespace MyWeb
{
public class Bootstrapper
{
public static void Run()
{
SetAutofacContainer();
AutoMapperConfiguration.Configure();
}
private static void SetAutofacContainer()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();
// Repositories
builder.RegisterAssemblyTypes(typeof(ProjectRepository).Assembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerRequest();
// Services
builder.RegisterAssemblyTypes(typeof(ProjectService).Assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerRequest();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
// Job.cs
namespace MyWeb
{
public class Job
{
public void DoWork()
{
IProjectService _projectService = DependencyResolver.Current.GetService<IProjectService>(); // ERROR
}
}
}
User contributions licensed under CC BY-SA 3.0