c# – Hangfire.Autofac与MVC应用程序注入失败

前端之家收集整理的这篇文章主要介绍了c# – Hangfire.Autofac与MVC应用程序注入失败前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个简单的Hangfire测试,但它不工作.以下是所有重要的代码,以及我如何使用Hangire.Autofac进行配置.不知道我在这里失踪了我在/ hangfire dashbaord进入的例外也在下面.
public class AmazonSqsService : IAmazonSqsService
{
    private readonly IBackgroundJobClient _backgroundJobClient;
    private readonly ILogService _logService;

    public AmazonSqsService(IBackgroundJobClient backgroundJobClient,ILogService logService) 
    {

        _backgroundJobClient. = backgroundJobClient;
        _logService= logService;
    }

    public async Task<string> Test()
    {

        return _backgroundJobClient.Enqueue(() => Looper());

    }

    public void Looper() {
        while (true) { _logService.Info("In Looper Loop"); Thread.Sleep(5000); } 
    } 
}

 public partial class Startup
{
    public static IContainer ConfigureContainer()
    {
        var builder = new ContainerBuilder();
        RegisterApplicationComponents(builder);
        AppGlobal.Container = builder.Build();
    }

    public static void RegisterApplicationComponents(ContainerBuilder builder)
    {
        builder.RegisterType<LogService>().As<ILogService>().InstancePerLifetimeScope();
        builder.RegisterType<AmazonSqsService>().As<IAmazonSqsService>().InstancePerLifetimeScope();
        builder.RegisterType<BackgroundJobClient>().As<IBackgroundJobClient>().InstancePerLifetimeScope();
        builder.Register(c => JobStorage.Current).As<JobStorage>().InstancePerLifetimeScope();
        builder.Register(c => new StateMachineFactory(JobStorage.Current)).As<IStateMachineFactory>().InstancePerLifetimeScope();

    }

    public static void ConfigureHangfire(IAppBuilder app) 
    {
        app.UseHangfire(config =>
        {
            config.UseAutofacActivator(AppGlobal.Container);
            config.UsesqlServerStorage("DefaultDatabase");
            config.UseServer();
        });
    }
}

但是在仪表板中,我不断得到这个错误的任务:

Failed An exception occurred during job activation.
Autofac.Core.Registration.ComponentNotRegisteredException

The requested service ‘App.Services.AmazonSqsService’ has not been registered. To avoid this exception,either register a component to provide the service,check for service registration using IsRegistered(),or use the ResolveOptional() method to resolve an optional dependency.

解决方法

最终确定了这一点.

正确使用方法

public class Service : IService {
      public void MethodToQueue() { ... }
}

public class AnyOtherClass {
     public void StartTasks() {
          BackgroundJob.Enqueue<IService>(x => x.MethodToQueue()); //Good
     } 
}

使用不当(我做错了什么)

public class Service : IService {
     public void StartTasks() {
          BackgroundJob.Enqueue(() => this.MethodToQueue()); //Bad
     } 

      public void MethodToQueue() { ... }
}

public class AnyOtherClass {
     public AnyOtherClass(IService service) {
          service.StartTasks();
     }
}
原文链接:https://www.f2er.com/csharp/96424.html

猜你在找的C#相关文章