我实际上在使用 NInject 进行依赖注入(inject)的 ASP.Net MVC 4 Web 应用程序中工作。我们还使用基于 Entity Framework 的 UnitOfWork 和存储库。
我们想在我们的应用程序中使用 Quartz.net 来定期启动一些自定义作业。我希望 NInject 自动绑定(bind)我们工作中需要的服务。
它可能是这样的:
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 绑定(bind)中配置如下(使用请求范围):
kernel.Bind<IDispatchingManagementService>().To<DispatchingManagementService>();
是否可以使用 NInject 将正确的实现注入(inject)到我们的自定义作业中?怎么做?我已经阅读了一些关于堆栈溢出的帖子,但是我需要一些建议和一些使用 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 将为您解决依赖关系。
关于asp.net - Quartz.net 和 Ninject : how to bind implementation to my job using NInject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25889255/