gpt4 book ai didi

c# - 使用 Quartz.NET 和简单注入(inject)器进行构造函数注入(inject)

转载 作者:行者123 更新时间:2023-12-03 03:23:50 25 4
gpt4 key购买 nike

目前我正在使用 Quartz.NET 编写一个服务来安排它的运行。

我想知道是否有人有使用 Quartz.NET 和简单注入(inject)器进行构造函数注入(inject)的经验。

以下基本上是我希望实现的目标

public class JobImplementation: IJob
{
private readonly IInjectedClass injectedClass;

public JobImplementation(IInjectedClass _injectedClass)
{
injectedClass = _injectedClass
}

public void Execute(IJobExecutionContext _context)
{
//Job code
}

最佳答案

根据this blog post ,您需要实现一个自定义的 IJobFactory,如下所示:

public class SimpleInjectorJobFactory : IJobFactory
{
private readonly Container container;
private readonly Dictionary<Type, InstanceProducer> jobProducers;

public SimpleInjectorJobFactory(
Container container, params Assembly[] assemblies)
{
this.container = container;

// By creating producers, jobs can be decorated.
var transient = Lifestyle.Transient;
this.jobProducers =
container.GetTypesToRegister(typeof(IJob), assemblies).ToDictionary(
type => type,
type => transient.CreateProducer(typeof(IJob), type, container));
}

public IJob NewJob(TriggerFiredBundle bundle, IScheduler _)
{
var jobProducer = this.jobProducers[bundle.JobDetail.JobType];
return new AsyncScopedJobDecorator(
this.container, () => (IJob)jobProducer.GetInstance());
}

public void ReturnJob(IJob job)
{
// This will be handled automatically by Simple Injector
}

private sealed class AsyncScopedJobDecorator : IJob
{
private readonly Container container;
private readonly Func<IJob> decorateeFactory;

public AsyncScopedJobDecorator(
Container container, Func<IJob> decorateeFactory)
{
this.container = container;
this.decorateeFactory = decorateeFactory;
}

public async Task Execute(IJobExecutionContext context)
{
using (AsyncScopedLifestyle.BeginScope(this.container))
{
var job = this.decorateeFactory();
await job.Execute(context);
}
}
}
}

此外,您还需要进行以下注册:

var container = new Container();

container.Options.ScopedLifestyle = new AsyncScopedLifestyle();

var factory = new StdSchedulerFactory();

IScheduler scheduler = await factory.GetScheduler();

scheduler.JobFactory = new SimpleInjectorJobFactory(
container,
Assembly.GetExecutingAssembly()); // assemblies that contain jobs

// Optional: register some decorators
container.RegisterDecorator(typeof(IJob), typeof(LoggingJobDecorator));

container.Verify();

关于c# - 使用 Quartz.NET 和简单注入(inject)器进行构造函数注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2212206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com