如何创建一个Quartz.NET的工作,需要注射autofac [英] How do I create a Quartz.NET’s job requiring injection with autofac

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

问题描述

我试图让Quartz.net(2.1.2)与IoC容器(autofac)的工作,因为我有我需要在调度作业使用的服务。我发现关于这个问题类似的职位,但我似乎无法找到一个与autofac特定登记的例子。

与我有同样的问题,以下岗位涉及:

如何安排使用Quartz.net 2.0任务?

不过,我相信我缺少的部分是当回答说不要忘记注册在IoC容器的工作。我不确定如何准确做到这一点,因为一切我都试过到目前为止还没有工作。

在下面的例子中,HelloJob将运行,但每当我试图将releaseService注入ReleaseJob它拒绝运行。

更新:
我标志着DependencyRegistration.cs部分,在那里,我相信这个问题是code。

更新2:
这都涉及到什么,我需要做的,可能会帮助一些相关的链接(我已经通过他们都走了,但仍然无法弄清楚如何获得与autofac这方面的工作):

如何PRO方式使用Quartz.NET?
- <一个href=\"http://blog.goyello.com/2009/09/21/how-to-use-quartz-net-in-pro-way/\">http://blog.goyello.com/2009/09/21/how-to-use-quartz-net-in-pro-way/

Autofac和Quartz.NET
- <一个href=\"http://blog.humann.info/post/2013/01/30/Autofac-and-QuartzNET.aspx\">http://blog.humann.info/post/2013/01/30/Autofac-and-QuartzNET.aspx

构造注射Quartz.NET和简单喷油器
- <一个href=\"http://stackoverflow.com/questions/14562176/constructor-injection-with-quartz-net-and-simple-injector/14562660#14562660\">Constructor注射Quartz.NET和简单喷油

ASP.Net MVC 3,Ninject和Quartz.Net - 如何
- <一个href=\"http://stackoverflow.com/questions/6741599/asp-net-mvc-3-ninject-and-quartz-net-how-to\">ASP.Net MVC 3,Ninject和Quartz.Net - 如何

下面是相关code:

的Global.asax

 保护无效的Application_Start()
    {
        AreaRegistration.RegisterAllAreas();        RegisterGlobalFilters(GlobalFilters.Filters);
        的RegisterRoutes(RouteTable.Routes);        VAR dependencyRegistration =新DependencyRegistration();
        dependencyRegistration.Register();        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(新FluentValidationModelValidatorProvider(新ValidatorFactory()));        DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = FALSE;
    }

DependencyRegistration.cs

 公共类DependencyRegistration
{
    公共无效寄存器()
    {
        VAR建设者=新ContainerBuilder();        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());        //验证
        builder.RegisterType&LT; ValidatorFactory&GT;()
            。至于&LT; IValidatorFactory&GT;()
            .InstancePerHtt prequest();        AssemblyScanner findValidatorsInAssembly = AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly());
        的foreach(在findValidatorsInAssembly AssemblyScanner.AssemblyScanResult项)
        {
            builder.RegisterType(item.ValidatorType)
                。至于(item.InterfaceType)
                .InstancePerHtt prequest();
        }        //时间表
        builder.Register。(X =方式&gt;新StdSchedulerFactory()的getScheduler())为&lt; IScheduler&GT;();        //调度作业
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()),其中(X =&GT; typeof运算(IJob).IsAssignableFrom(X))。        变种容器= builder.Build();
        DependencyResolver.SetResolver(新AutofacDependencyResolver(容器));        //时间表
        IScheduler章附表= container.Resolve&LT; IScheduler&GT;();
        sched.JobFactory =新AutofacJobFactory(容器);
        sched.Start();        IJobDetail工作= JobBuilder.Create&LT; ReleaseJob&GT;()
                .WithIdentity(1Job)
                。建立();        ITrigger触发= TriggerBuilder.Create()
            .WithIdentity(1JobTrigger)
            .WithSimpleSchedule(X =&X的催化剂
                .RepeatForever()
                .WithIntervalInSeconds(5)
            )
            。现在开始()
            。建立();        sched.ScheduleJob(作业,触发);        工作= JobBuilder.Create&LT; HelloJob&GT;()
               .WithIdentity(2Job)
               。建立();        触发= TriggerBuilder.Create()
            .WithIdentity(2JobTrigger)
            .WithSimpleSchedule(X =&X的催化剂
                .RepeatForever()
                .WithIntervalInSeconds(5)
            )
            。现在开始()
            。建立();        sched.ScheduleJob(作业,触发);
    }
}

JobFactory.cs

 公共类AutofacJobFactory:IJobFactory
{
    私人只读的IContainer _container;    公共AutofacJobFactory(集装箱的IContainer)
    {
        _container =容器;
    }    公共IJob NewJob(TriggerFiredBundle捆绑,IScheduler调度)
    {
        回报(IJob)_container.Resolve(bundle.JobDetail.JobType);
    }    公共无效ReturnJob(IJob工作)
    {
    }
}

ReleaseJob.cs

 公共类ReleaseJob:IJob
{
    私人只读IReleaseService _releaseService;    公共ReleaseJob(IReleaseService releaseService)
    {
        this._releaseService = releaseService;
    }    公共无效执行(IJobExecutionContext上下文)
    {
        的Debug.WriteLine(+ DateTime.Now.ToString()发行于运行);
    }
}公共类HelloJob:IJob
{
    公共无效执行(IJobExecutionContext上下文)
    {
        的Debug.WriteLine(你好在工作+ DateTime.Now.ToString());
    }
}

ReleaseServiceModel.cs

 公共类ReleaseServiceModule:模块
{
    保护覆盖无效负载(ContainerBuilder建设者)
    {
        builder.RegisterType&LT; ReleaseService&GT;()
            。至于&LT; IReleaseService&GT;()
            .InstancePerLifetimeScope();
    }
}


解决方案

我终于找到了什么问题了。

我的发布服务使用其与不同的范围内创建一个数据存储库。

我通过创建什么也没做,但返回一个字符串一个新的测试服务发现这一点,而这工作被注入到石英工作。

在发现这个,我改变了发布服务呼吁库的范围,然后发布服务开始石英作业里面工作。

我道歉对任何人看了这个问题,试图帮助我。因为发布服务的code的未上市,就已经很难弄清楚什么是错的。

我已经更新了code。与我用来与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:

How to schedule task using Quartz.net 2.0?

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.

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

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

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):

HOW TO use Quartz.NET in PRO way? - http://blog.goyello.com/2009/09/21/how-to-use-quartz-net-in-pro-way/

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

Constructor injection with Quartz.NET and Simple Injector - Constructor injection with Quartz.NET and Simple Injector

ASP.Net MVC 3, Ninject and Quartz.Net - How to? - ASP.Net MVC 3, Ninject and Quartz.Net - How to?

Here is the relevant code:

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.

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

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

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