Dependency Injection on a Job with Autofac

Apr 17, 2015 at 9:35 PM
How do I get Atlas and Autofac to "play well together"
If I have a Job with constructor injection the Job won't be executed.
But that same job with a default constructor executes.

My code is similar to this:
http://markjourdan.name/a-quick-way-to-create-a-windows-service-using-autofac-quartz-and-atlas

But my MyJob is injecting a new IMyInterface.
Coordinator
Apr 20, 2015 at 3:48 PM
The implementation of IJob is instantiated via Quartz, so if you want to use Atlas and Autofac to use constructor injection on your Job, you will need to implement and register the JobFactory interface from Quartz. I don't have a code example handy, if you give me a couple of days I will throw one together.
Coordinator
Apr 20, 2015 at 3:48 PM
Another option is to allow your interface to be property injected.
Apr 20, 2015 at 5:22 PM
When I registered by job in autofac, I needed to add the AsSelf() ex:
  builder.RegisterType<MyJob>().AsSelf().As<IJob>();
as well as create a custom Job Factory like this:
public class IoCJobFactory : IJobFactory
{
    readonly IContainer _container;

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

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        try
        {            
            // Return job that is registered in container
            return (IJob)_container.Resolve(bundle.JobDetail.JobType);
        }
        catch (Exception e)
        {
            var se = new SchedulerException("Problem instantiating class", e);
            throw se;
        }
    }

    public void ReturnJob(IJob job)
    {
        throw new NotImplementedException();
    }
}
Coordinator
Apr 26, 2015 at 7:20 PM
Yea, this will do it.

When you do this, please be careful how you register your components. Since each call to NewJob will be using the same root container, everything will be resolved in that container as well. If you want to execute jobs in separate containers you will have to do some more work than just this.