Please go through the below scenario. This is based on C# .Net Web API.
I have to call GetMonthlyData()
which is located in BL layer. BL Layer related dependencies are initialized in the Controller and it works fine.
It is required to call the same GetMonthlyData()
as a Job and I am using Quartz for that. However when initiating the Job I am getting an issue since the dependencies are not resolved at that time since the call does not goes through the controller. How can I resolve this issue?
FileProcessController.cs -> This is the controller which initiates the Dependency Injection
[RoutePrefix("api/FileProcess")]
public class FileProcessController : ApiController
{
private readonly IFileProcessManager _fileProcessManager;
public FileProcessController(IFileProcessManager fileProcessManager)
{
this._fileProcessManager = fileProcessManager;
}
[HttpGet]
[Route("MontlyData")]
public MonthlyProcessDataDM GetMonthlyData()
{
try
{
var result = this._fileProcessManager.GetMonthlyData();
return result;
}
catch (Exception ex)
{
throw ExceptionStatusCode.ThrowHttpErrorResponseAndMessage(ex);
}
}
}
}
FileProcessManager.cs -> This contains the implementation of GetMonthlyData()
public class FileProcessManager : IFileProcessManager
{
public FileProcessManager(IFileProcessManagerRepo ifileProcessManagerRepo)
{
}
public MonthlyProcessDataDM GetMonthlyData()
{
//Code to be executed
}
}
Interface IFileProcessManager
public interface IFileProcessManager
{
MonthlyProcessDataDM GetMonthlyData();
}
Execution of the above flow works properly. In the next scenario, I need to call GetMonthlyData()
using Quartz. For that
Global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
JobScheduler.Start(); // This is the scheduler for the above mentioned job.
}
JobScheduler.cs
public class JobScheduler
{
public static void Start()
{
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();
IJobDetail job = JobBuilder.Create<MonthlyProcessManager>().Build(); // This is the Implementation
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(10)
.RepeatForever())
.Build();
scheduler.ScheduleJob(job, trigger);
}
}
I tried to implement as below to resolve the dependency injection, However it throws null reference exception pointing the dependency injection code.
MonthlyProcessManager.cs
public class MonthlyProcessManager : Quartz.IJob
{
public IFileProcessManager _fileProcessManager;
public MonthlyProcessManager(IFileProcessManager fileProcessManager)
{
_fileProcessManager = fileProcessManager;
}
public void Execute(Quartz.IJobExecutionContext context)
{
MonthlyProcessDataDM monthlyProcessDataVM = _fileProcessManager.GetMonthlyData();
}
}
How can I resolve this issue. Thanks in advance.