Solved

How do I create a Quartz.NET’s job requiring injection with autofac

Posted on 2013-06-07
3
4,641 Views
Last Modified: 2013-06-10
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.

In the following example, the "HelloJob" will run, but whenever I try to inject the releaseService into the "ReleaseJob" it refuses to run. If I remove the ReleaseService references from the ReleaseJob it will then work.

The part I believe I have wrong is the bindings. I'm not very experienced with them, but I've tried every possible thing I can think of and it just refuses to work.

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

Note that I have also tried getting the scheduler in the DependencyRegistration.cs file with:

//Schedule
IScheduler scheduler = container.Resolve<ISchedulerFactory>().GetScheduler();

...instead of using a new StdSchedulerFactory(), but that doesn't work either.

Update:
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 it 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
http://stackoverflow.com/questions/14562176/constructor-injection-with-quartz-net-and-simple-injector/14562660#14562660
How to schedule task using Quartz.net 2.0?
http://stackoverflow.com/questions/16653178/how-to-schedule-task-using-quartz-net-2-0
ASP.Net MVC 3, Ninject and Quartz.Net - How to?
http://stackoverflow.com/questions/6741599/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;
    }

Open in new window


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));
        /*** Scheduler ***/

        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);
    }
}

Open in new window


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)
    {
    }
}

Open in new window


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());
    }
}

Open in new window


ReleaseServiceModel.cs

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

Open in new window

0
Comment
Question by:verytoothy
3 Comments
 

Accepted Solution

by:
verytoothy earned 0 total points
ID: 39236398
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.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now