如何使用Quartz.net和Log4net配置ninject

时间:2018-10-12 06:03:33

标签: c# ninject log4net quartz.net

我尝试使quartzlog4netninject一起使用。

Ninjectlog4net(无quartz)的搭配完美。

但是当我与Quartz一起使用时,作业已执行但记录器无法正常工作。 (空控制台)

下面是Ninject配置:

var kernel = new StandardKernel();

kernel.Load(Assembly.GetExecutingAssembly());

kernel.Bind<ILog>().ToMethod(x => LogManager.GetLogger(x.Request.Target != null
                        ? x.Request.Target.Member.DeclaringType
                        : x.Request.Service));

kernel.Bind<IScheduler>().ToMethod(x =>
{
    ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
    var sched = schedulerFactory.GetScheduler().Result;
    sched.JobFactory = new NinjectJobFactory(kernel);
    return sched;
}); 

和ninjetJobFactory:

class NinjectJobFactory : SimpleJobFactory
{
    readonly IKernel _kernel;

    public NinjectJobFactory(IKernel kernel)
    {
        this._kernel = kernel;
    }

    public override IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        try
        {
            // this will inject dependencies that the job requires
            return (IJob)this._kernel.Get(bundle.JobDetail.JobType);
        }
        catch (Exception e)
        {
            throw new SchedulerException(string.Format("Problem while instantiating job '{0}' from the NinjectJobFactory.", bundle.JobDetail.Key), e);
        }
    }
}

我使用this article使Quarts与ninject一起工作。

我制作了simple working example,您可以从github下载它进行测试。

感谢帮助。

1 个答案:

答案 0 :(得分:2)

在研究该问题时,我意识到,通过在解决调度程序之前简单地从内核解决ILog似乎是可行的。至于为什么我有点不确定。

但是我确实注意到所使用的Quartz版本具有异步API,因此在调查问题期间必须进行一些更改。

在链接文档的注释中,建议重构为新的异步API语法

kernel.Bind<Task<IScheduler>>().ToMethod(async _ => {
    ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
    var sched = await schedulerFactory.GetScheduler();
    sched.JobFactory = new NinjectJobFactory(kernel);
    return sched;
});

我通过创建一个在启动调度程序时讲述异步API优势的服务来对此进行了改进。

public interface IService {
    Task Start();
}

public class Service : IService {
    private readonly IJobFactory jobFactory;
    private readonly ILog log;
    private readonly ISchedulerFactory schedulerFactory;

    public Service(IJobFactory jobFactory, ISchedulerFactory schedulerFactory, ILog log) {
        this.jobFactory = jobFactory;
        this.schedulerFactory = schedulerFactory;
        this.log = log;
    }

    public async Task Start() {
        IScheduler scheduler = await schedulerFactory.GetScheduler();
        scheduler.JobFactory = jobFactory;

        IJobDetail job = JobBuilder.Create()
           .OfType<SimpleJob>()
           .Build();

        ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("trigger1", "group1")
            .StartNow()
            .WithSimpleSchedule(x => x.WithIntervalInSeconds(3)
                .RepeatForever())
            .Build();

        await scheduler.ScheduleJob(job, trigger);

        await scheduler.Start();

        log.Debug("Scheduler started");
    }
}

我创建了一个引导程序,并使用NinjectModule来正确组织依赖项注入

public class Bootstrapper {
    public IKernel Init() {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());

        kernel.Bind<IServiceProvider>().ToConstant(kernel);

        return kernel;
    }
}

public class LoggingModule : NinjectModule {
    public override void Load() {
        Bind<ILog>()
            .ToMethod(x => LogManager.GetLogger(
                x.Request.Target != null ? x.Request.Target.Member.DeclaringType : x.Request.Service)
            );
    }
}

public class QuartzModule : NinjectModule {
    public override void Load() {
        Bind<IJobFactory>().To<NinjectJobFactory>();
        Bind<ISchedulerFactory>().To<StdSchedulerFactory>();
        Bind<IService>().To<Service>();
    }
}

class NinjectJobFactory : IJobFactory {
    readonly IServiceProvider provider;

    public NinjectJobFactory(IServiceProvider provider) {
        this.provider = provider;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) {
        IJobDetail jobDetail = bundle.JobDetail;
        Type jobType = jobDetail.JobType;
        try {
            // this will inject any dependencies that the job requires
            var value = (IJob)provider.GetService(jobType);
            return value;
        } catch (Exception e) {
            throw new SchedulerException(string.Format("Problem while instantiating job '{0}' from the NinjectJobFactory.", bundle.JobDetail.Key), e);
        }
    }

    /// <summary>
    /// Allows the job factory to destroy/cleanup the job if needed. 
    /// No-op when using SimpleJobFactory.
    /// </summary>
    public void ReturnJob(IJob job) {
        var disposable = job as IDisposable;
        disposable?.Dispose();
    }
}

进行修改并相应地更新主程序

class Program {
    static void Main(string[] args) {
        Bootstrapper bootstrapper = new Bootstrapper();
        var kernel = bootstrapper.Init();

        WithQuartz(kernel).GetAwaiter().GetResult();

        Console.ReadKey();
    }

    public static Task WithQuartz(IKernel kernel) {
        var service = kernel.Get<IService>();
        return service.Start();
    }
}

一切似乎都按预期进行。