如何创建需要使用 autofac 注入的 Quartz.NET 作业 [英] How do I create a Quartz.NET’s job requiring injection with autofac

查看:29
本文介绍了如何创建需要使用 autofac 注入的 Quartz.NET 作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 Quartz.net (2.1.2) 与 IoC 容器 (autofac) 一起工作,因为我有需要在预定作业中使用的服务.我找到了有关该主题的类似帖子,但似乎找不到带有 autofac 特定注册示例的帖子.

I am trying to get Quartz.net (2.1.2) to work with an IoC container (autofac), as I have services I need to use in the scheduled jobs. I have found similar posts on the subject, but I can't seem to find one with a specific registration example for autofac.

以下帖子涉及我遇到的相同问题:

The following post deals with the same issue I am having:

如何使用 Quartz.net 2.0 调度任务?

但是,我认为我缺少的部分是当答案说并且不要忘记在 IoC 容器中注册作业"时.我不确定如何确切地做到这一点,因为到目前为止我尝试过的一切都没有奏效.

However, the part I believe I am missing is when the answer says "And don't forget to register the job in the IoC container". I am unsure how to do this exactly, as everything I have tried so far hasn't worked.

在下面的示例中,HelloJob"将运行,但每当我尝试将 releaseService 注入ReleaseJob"时,它拒绝运行.

In the following example, the "HelloJob" will run, but whenever I try to inject the releaseService into the "ReleaseJob" it refuses to run.

更新:我在 DependencyRegistration.cs 部分标记了我认为问题所在的代码.

Update: I marked the code in the DependencyRegistration.cs section where I believe the issue is.

更新 2:一些与我需要做的事情相关的相关链接,可能会有所帮助(我已经浏览了所有链接,但仍然无法弄清楚如何使用 autofac 使其工作):

Update 2: Some related links that are related to what I need to do and might help (I've already gone through them all but still cannot figure out how to get this working with autofac):

如何以专业的方式使用 Quartz.NET?- http://blog.goyello.com/2009/09/21/how-to-use-quartz-net-in-pro-way/

Autofac 和 Quartz.NET- http://blog.humann.info/post/2013/01/30/Autofac-and-QuartzNET.aspx

使用 Quartz.NET 和 Simple Injector 进行构造函数注入- 使用 Quartz.NET 和 Simple Injector 进行构造函数注入

ASP.Net MVC 3、Ninject 和 Quartz.Net - 如何?- ASP.Net MVC 3、Ninject 和 Quartz.Net- 如何?

相关代码如下:

Global.asax

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        var dependencyRegistration = new DependencyRegistration();
        dependencyRegistration.Register();

        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new ValidatorFactory()));

        DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
    }

DependencyRegistration.cs

public class DependencyRegistration
{
    public void Register()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

        // Validation
        builder.RegisterType<ValidatorFactory>()
            .As<IValidatorFactory>()
            .InstancePerHttpRequest();

        AssemblyScanner findValidatorsInAssembly = AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly());
        foreach (AssemblyScanner.AssemblyScanResult item in findValidatorsInAssembly)
        {
            builder.RegisterType(item.ValidatorType)
                .As(item.InterfaceType)
                .InstancePerHttpRequest();
        }

        // Schedule
        builder.Register(x => new StdSchedulerFactory().GetScheduler()).As<IScheduler>();

        // Schedule jobs
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(x => typeof(IJob).IsAssignableFrom(x));

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        //Schedule
        IScheduler sched = container.Resolve<IScheduler>();
        sched.JobFactory = new AutofacJobFactory(container);
        sched.Start();

        IJobDetail job = JobBuilder.Create<ReleaseJob>()
                .WithIdentity("1Job")
                .Build();

        ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("1JobTrigger")
            .WithSimpleSchedule(x => x
                .RepeatForever()
                .WithIntervalInSeconds(5)
            )
            .StartNow()
            .Build();

        sched.ScheduleJob(job, trigger);

        job = JobBuilder.Create<HelloJob>()
               .WithIdentity("2Job")
               .Build();

        trigger = TriggerBuilder.Create()
            .WithIdentity("2JobTrigger")
            .WithSimpleSchedule(x => x
                .RepeatForever()
                .WithIntervalInSeconds(5)
            )
            .StartNow()
            .Build();

        sched.ScheduleJob(job, trigger);
    }
}

JobFactory.cs

public class AutofacJobFactory : IJobFactory
{
    private readonly IContainer _container;

    public AutofacJobFactory(IContainer container)
    {
        _container = container;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        return (IJob)_container.Resolve(bundle.JobDetail.JobType);
    }

    public void ReturnJob(IJob job)
    {
    }
}

ReleaseJob.cs

public class ReleaseJob : IJob
{
    private readonly IReleaseService _releaseService;

    public ReleaseJob(IReleaseService releaseService)
    {
        this._releaseService = releaseService;
    }

    public void Execute(IJobExecutionContext context)
    {
        Debug.WriteLine("Release running at " + DateTime.Now.ToString());
    }
}

public class HelloJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        Debug.WriteLine("Hello job at " + DateTime.Now.ToString());
    }
}

ReleaseServiceModel.cs

public class ReleaseServiceModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<ReleaseService>()
            .As<IReleaseService>()
            .InstancePerLifetimeScope();
    }
}

推荐答案

我终于找到了问题所在.

I finally tracked down what the issue was.

我的发布服务使用了一个以不同范围创建的数据存储库.

My release service was using a data repository which was being created with a different scope.

我通过创建一个新的测试服务发现了这一点,该服务只返回一个字符串,并且被注入到一个石英作业中.

I discovered this by creating a new test service that did nothing but return a string, and that worked being injected into a quartz job.

发现这一点后,我更改了发布服务调用的存储库的范围,然后发布服务开始在石英作业中工作.

On discovering this, I changed the scope of the repository called upon by the release service , and then the release service started working inside the quartz job.

我向任何看到这个问题并试图帮助我的人道歉.因为没有列出发布服务的代码,所以很难找出问题所在.

My apologies to anyone that looked at this question to try and help me out. Because the code of the release service was not listed, it would have been difficult to figure out what was wrong.

我已经使用 autofac 用于石英的最终工作绑定更新了代码.

I have updated the code with the final working bindings I used for quartz with autofac.

这篇关于如何创建需要使用 autofac 注入的 Quartz.NET 作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆