First step - you need to tell StructureMap how to handle Quartz.net-related types.
Here's how I did it:
public class QuartzRegistry : Registry
{
public QuartzRegistry()
{
Scan(s =>
{
s.TheCallingAssembly();
s.WithDefaultConventions();
s.AddAllTypesOf<IJob>().NameBy(c => c.Name);
});
SelectConstructor(() => new StdSchedulerFactory());
For<ISchedulerFactory>().Use<StdSchedulerFactory>();
For<IScheduler>().Use(ctx => ctx.GetInstance<ISchedulerFactory>().GetScheduler());
}
}
and then pass that to the container:
public class MyContainer : Container
{
public MyContainer()
{
Configure(x => x.AddRegistry<CommonRegistry>());
}
}
This config should get all your IJob implementations.
Second - you need to implement IJobFactory via SM and tell your application to find it:
public class StructureMapJobFactory : IJobFactory
{
private IContainer container;
public StructureMapJobFactory()
{
container = new MyContainer();
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
try
{
return (IJob)container.GetInstance(bundle.JobDetail.JobType);
}
catch (Exception e)
{
throw new SchedulerException("Problem instantiating class", e);
}
}
public void ReturnJob(IJob job)
{
throw new NotImplementedException();
}
}
then you add following lines to your Web or App.config:
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<quartz>
<add key="quartz.scheduler.jobFactory.type" value="QuartzFacilities.StructureMapJobFactory, QuartzFacilities" />
</quartz>
And you're almost set. Now to the final part.
You add this code to try things out:
class SchedulerProgram
{
public static void Main(string[] args)
{
var container = new MyContainer();
var scheduler = container.GetInstance<IScheduler>();
scheduler.Start();
ITrigger trigger = TriggerBuilder.Create()
.WithDescription("Every 5 seconds")
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(5)
.RepeatForever()
)
.Build();
scheduler.ScheduleJob(new JobDetailImpl("myJobDetail", typeof(ConsoleJob)), trigger);
Console.ReadKey();
}
}
ConsoleJob is just trivial class used for testing:
public class ConsoleJob: IJob
{
public void Execute(IJobExecutionContext context)
{
Console.WriteLine(DateTime.Now);
}
}
Hope that answers your question.
вторник, 8 апреля 2014 г., 17:53:00 UTC+4 пользователь Dhananjay Suryawanshi написал: