Конфигурация Autofac для зависания
Я хочу использовать Hangfire в моем приложении Asp.Net MVC, и я использую Autofac в качестве DI.
Я установил Hangfire.Autofac nuget.
Я хочу добавить такую повторяющуюся работу:
UserService.cs
public class UserService : IUserService
{
public void MyRecurringJob() { // do something here }
}
startup.cs
[assembly: OwinStartup(typeof(MyApp.Web.Startup))]
namespace MyApp.Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var AutofacContainer = AutofacDependencyResolver.Current.ApplicationContainer;
GlobalConfiguration.Configuration.UseSqlServerStorage("AppDbContext").UseAutofacActivator(AutofacContainer);
app.UseHangfireDashboard("/jobs");
app.UseHangfireServer();
var _user = DependencyResolver.Current.GetService<IUserService>();
RecurringJob.AddOrUpdate("SyncUsers", () => _user.MyRecurringJob(), Cron.Hourly());
}
}
}
И я получаю такую ошибку:
Unable to resolve the type 'MyApp.Core.Service.UserService' because the lifetime scope it belongs in can't be located. The following services are exposed by this registration: - MyApp.Core.Service.UserService Details
Autofac.Core.DependencyResolutionException: Unable to resolve the type 'MyApp.Core.Service.UserService' because the lifetime scope it belongs in can't be located. The following services are exposed by this registration:
- MyApp.Core.Service.UserService
Details ---> Autofac.Core.DependencyResolutionException: No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.
If you see this during execution of a web application, it generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario). Under the web integration always request dependencies from the dependency resolver or the request lifetime scope, never from the container itself.
1 ответ
Я не могу его сейчас протестировать, но чтобы зарегистрировать повторяющееся задание с Hangfire и Autofac, вам следует написать
RecurringJob.AddOrUpdate<UserService>("SyncUsers", (user) => user.MyRecurringJob(), Cron.Hourly());