How to use Ninject with FluentScheduler

Today i struggled a little with using Ninject with FluentScheduler.I wanted to have unique repositories and dispose behaviour between jobs to not strain memory of the application. I tried to find sophisticated solution to this problem by trying to find good scope to use InScope method from Ninject. At last I found out that it is the best to KISS this problem.

 

 

Firstly we will create base abstract class for all job classes that will use ninject.

 public abstract class NinjectableJob : IJob
    {
        protected IKernel kernel;

        public void Execute()
        {
            using(kernel = new StandardKernel())
            {
                NinjectSingletonCommon.RegisterTypes(kernel);
                execute();
            }
        }

        protected abstract void execute(); 
    }

To get advantage of auto dispose behaviour in Ninject all our bindings should use InSingletonScope. It guarantees calling dispose method on all created objects after disposing kernel.
RegisterTypes method in NinjectSingletonCommon contains only bindings like:

kernel.Bind<Test>().ToSelf().InSingletonScope();

From now on jobs that will need to use Ninject will need to inherit NinjectableJob. Very easy solution.

Leave a Reply

Your email address will not be published. Required fields are marked *