加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – Quartz.net和Ninject:如何使用NInject将实现绑定到

发布时间:2020-12-16 09:13:40 所属栏目:asp.Net 来源:网络整理
导读:我实际上在ASP.Net MVC 4 Web应用程序中工作,我们使用NInject进行依赖注入.我们还使用基于Entity框架的UnitOfWork和Repositories. 我们想在我们的应用程序中使用Quartz.net定期启动一些自定义作业.我希望NInject自动绑定我们工作中需要的服务. 它可能是这样
我实际上在ASP.Net MVC 4 Web应用程序中工作,我们使用NInject进行依赖注入.我们还使用基于Entity框架的UnitOfWork和Repositories.

我们想在我们的应用程序中使用Quartz.net定期启动一些自定义作业.我希望NInject自动绑定我们工作中需要的服务.

它可能是这样的:

public class DispatchingJob : IJob
{
    private readonly IDispatchingManagementService _dispatchingManagementService;

    public DispatchingJob(IDispatchingManagementService dispatchingManagementService )
    {
         _dispatchingManagementService = dispatchingManagementService ;
    }

    public void Execute(IJobExecutionContext context)
    {
         LogManager.Instance.Info(string.Format("Dispatching job started at: {0}",DateTime.Now));
        _dispatchingManagementService.DispatchAtomicChecks();
        LogManager.Instance.Info(string.Format("Dispatching job ended at: {0}",DateTime.Now));
    }
}

到目前为止,在我们的NInjectWebCommon绑定中配置如下(使用请求范围):

kernel.Bind<IDispatchingManagementService>().To<DispatchingManagementService>();

是否可以使用NInject将正确的实现注入我们的自定义作业?怎么做?我已经阅读了很少关于堆栈溢出的帖子,但是我需要一些建议和一些使用NInject的例子.

解决方法

在Quartz计划中使用JobFactory,并在那里解析您的作业实例.

所以,在你的NInject配置中设置工作(我在这里猜测正确的NInject语法)

// Assuming you only have one IJob
kernel.Bind<IJob>().To<DispatchingJob>();

然后,创建一个JobFactory:[编辑:这是@BatteryBackupUnit’s answer here的修改版本]

public class NInjectJobFactory : IJobFactory
{
    private readonly IResolutionRoot resolutionRoot;

    public NinjectJobFactory(IResolutionRoot resolutionRoot)
    {
        this.resolutionRoot = resolutionRoot;
    }

    public IJob NewJob(TriggerFiredBundle bundle,IScheduler scheduler)
    {
        // If you have multiple jobs,specify the name as
        // bundle.JobDetail.JobType.Name,or pass the type,whatever
        // NInject wants..
        return (IJob)this.resolutionRoot.Get<IJob>();
    }

    public void ReturnJob(IJob job)
    {
        this.resolutionRoot.Release(job);
    }
}

然后,在创建调度程序时,将JobFactory分配给它:

private IScheduler GetSchedule(IResolutionRoot root)
{
    var schedule = new StdSchedulerFactory().GetScheduler();

    schedule.JobFactory = new NInjectJobFactory(root);

    return schedule;
}

然后Quartz将使用JobFactory创建作业,NInject将为您解析依赖项.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读