【问题标题】:Autofac configuration for hangfire用于hangfire的Autofac配置
【发布时间】:2019-12-11 05:56:06
【问题描述】:

我想在我的 Asp.Net MVC 应用程序中使用 hangfire,并且我正在使用 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.

【问题讨论】:

    标签: c# asp.net-mvc autofac hangfire hangfire-autofac


    【解决方案1】:

    我现在无法对其进行测试,但是为了使用 Hangfire 和 Autofac 注册一个经常性的工作,您应该编写

    RecurringJob.AddOrUpdate<UserService>("SyncUsers", (user) => user.MyRecurringJob(), Cron.Hourly());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      相关资源
      最近更新 更多