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

江枫思渺然 提交于 2019-12-02 17:18:27

Create a JobFactory that uses Ninject

public class NinjectJobFactory : IJobFactory
{
    private readonly Func<Type, IJob> jobFactory;

    public NinjectJobFactory (Func<Type, IJob> jobFactory)
    {
        this.jobFactory = jobFactory;
    }

    public IJob NewJob(TriggerFiredBundle bundle)
    {
        return this.jobFactory(bundle.JobDetail.JobType);
    }
}

and a QuarzSchedulerProvider

public class QuartzSchedulerProvider : Provider<IScheduler> 
{
    private readonly IJobFactory jobFactory;
    private readonly IEnumerable<ISchedulerListener> listeners;
    private readonly ISchedulerFactory schedulerFactory;

    public QuartzSchedulerProvider(
        ISchedulerFactory schedulerFactory,
        IJobFactory jobFactory, 
        IEnumerable<ISchedulerListener> listeners)
    {
        this.jobFactory = jobFactory;
        this.listeners = listeners;
        this.schedulerFactory = schedulerFactory;
    }

    protected override IScheduler CreateInstance(IContext context)
    {
        var scheduler = this.schedulerFactory.GetScheduler();
        scheduler.JobFactory = this.jobFactory;
        foreach (var listener in this.listeners)
        {
            scheduler.AddSchedulerListener(listener);
        }

        return scheduler;
    }
}

and a SchedulerFactoryProvider

public class QuartzSchedulerFactoryProvider : Provider<ISchedulerFactory>
{
    protected override ISchedulerFactory CreateInstance(IContext context)
    {
        var properties = new NameValueCollection();
        properties["quartz.dataSource.DataSource.connectionString"] = "Your connection string";
        properties["quartz.dataSource.DataSource.provider"] = "Your provider";

        properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
        properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz ";
        properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
        properties["quartz.jobStore.dataSource"] = "DataSource";
        properties["quartz.jobStore.useProperties"] = "true";

        return new StdSchedulerFactory(properties);
    }
}

and configure

Bind<IJobFactory>().To<NinjectJobFactory>();
Bind<ISchedulerFactory>().ToProvider<QuartzSchedulerFactoryProvider>();
Bind<IScheduler>().ToProvider<QuartzSchedulerProvider>().InSingletonScope();
Bind<Func<Type, IJob>>().ToMethod(ctx => t => (IJob)ctx.Kernel.Get(t));

If you need some ISchedulerListener e.g. for logging bind them here too.

Inject an instance of IScheduler where you want to add Jobs and most likely you have to do property injection of an instance into global.asax too. But note I havn't used Quarz in MVC context yet as I think Scheduled Tasks do not belong into a Web App but rather into a service running on the same server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!