2

I have a project with three-level architecture:

  • project.Data
  • project.Domain
  • project.Web

I need to implement Quartz.Net to user interface level.

And use it following way:

 public class EmailSender : IJob
 {
     ISomeService _service;

     public EmailSender(ISomeService service)
     {
        _service = service;
     }

     public void Execute(IJobExecutionContext context)
     {
        _service.Create();
     }
 }

public class EmailScheduler
{
    public static void Start()
    {
        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        scheduler.Start();

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

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

        scheduler.ScheduleJob(job, trigger);       
    }
}

In global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {  
        EmailScheduler.Start();
    }
 }

In project.Data

I use pattern of repositories. As I use few repositories for each entity, I use Unit of Work pattern to make easier connection to database.

public interface IUnitOfWork : IDisposable
{
    ISomeRepository SomeRepository { get; }
    void Save();
}

EFUnitOfWork class in constructor receives string with name of connection, which will be sent to data context constructor So we will interact with database through EFUnitOfWork class.

public class EFUnitOfWork : IUnitOfWork
{
    private Context db;

    private SomeRepository _someRepository;

    public EFUnitOfWork(string connectionString)
    {
        db = new Context(connectionString);
    }

    public ISomeRepository SomeRepository 
    {
        get
        {
            if (_someRepository == null)
                _someRepository = new SomeRepository(db);
            return _someRepository;
        }
    }
}

In project.Domain

ServiceModule is a special module Ninject, which is used for organizing dependencies matching. It replaces EFUnitOfWork with IUnitOfWork.

public class ServiceModule : NinjectModule
{
    private string connectionString;
    public ServiceModule(string connection)
    {
        connectionString = connection;
    }
    public override void Load()
    {
        Bind<IUnitOfWork>().To<EFUnitOfWork>().WithConstructorArgument(connectionString);
    }
}

public interface ISomeService
{
    void Create();
}

public class SomeService : ISomeService
{
    IUnitOfWork Database { get; set; }

    public LetterService(IUnitOfWork uow)
    {
        Database = uow;
    }

    public void Create(){
    }
}

In project.Web

To set dependencies I use following class:

public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernel;
    public NinjectDependencyResolver(IKernel kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }
    public object GetService(Type serviceType)
    {
        return kernel.TryGet(serviceType);
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernel.GetAll(serviceType);
    }
    private void AddBindings()
    {
        kernel.Bind<ISomeService>().To<SomeService>();
    }
}

In App_Start folder

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(evenafter.WEB.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(evenafter.WEB.App_Start.NinjectWebCommon), "Stop")]

namespace project.WEB.App_Start
{
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;
using Util;
using Ninject.Modules;
using Domain.Infrastructure;
using Quartz.Impl;

public static class NinjectWebCommon 
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        // set connection string
        var modules = new INinjectModule[] { new ServiceModule("DefaultConnection") };
        var kernel = new StandardKernel(modules);
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            RegisterServices(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }

    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        System.Web.Mvc.DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }        
}
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
V.Klishin
  • 29
  • 1
  • 2
  • Hello, @BatteryBackupUnit sorry for disturbing, I noticed that you have answered at similar topic early. Could you take a look please? Thanks in advance – V.Klishin Feb 02 '17 at 08:50
  • 1
    Sorry, what's the actual question? There is a guide to Quartz.Net in MVC here.https://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net – CountZero Feb 02 '17 at 12:14
  • see http://stackoverflow.com/questions/28369444/c-sharp-net-mvc-4-how-do-i-create-quartz-jobs-that-use-ninject-services/28373290#28373290 and http://stackoverflow.com/questions/22810793/how-to-inject-quartzs-job-with-ninject/22812433#22812433 – BatteryBackupUnit Feb 02 '17 at 14:50
  • 1
    Possible duplicate of [c# .NET MVC 4 - How do I create Quartz jobs that use Ninject services?](http://stackoverflow.com/questions/28369444/c-sharp-net-mvc-4-how-do-i-create-quartz-jobs-that-use-ninject-services) – jjj Feb 04 '17 at 21:25

0 Answers0