使用InRequestScope进行与Ninject的Hangfire

时间:2016-08-07 17:34:06

标签: dependency-injection cron ninject hangfire hangfire.ninject

我已将Hangfire.Ninject包安装到ASP MVC 5应用程序,以便我可以运行一些后台作业。

我已经阅读了文档,但我对如何实现它感到困惑。

我现有的配置使用InRequestScope作为我的IUnitOfwork类,以确保每个HTTP请求只实例化一个实例,如下所示:

private static void RegisterServices(IKernel kernel)
{
        kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
 } 

要在我的ninjectwebcommon.cs类中按照以下文档使用ninject和hangfire:

 private static IKernel CreateKernel()
 {
        var kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            GlobalConfiguration.Configuration.UseNinjectActivator(kernel);

            RegisterServices(kernel);

        return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    private static void RegisterServices(IKernel kernel)
    {
         kernel.Bind<IUnitOfWork>()
            .ToSelf()
            .InNamedOrBackgroundJobScope(context => context.Kernel.Components.GetAll<INinjectHttpApplicationPlugin>()
            .Select(c => c.GetRequestScope(context))
            .FirstOrDefault(s => s != null));

    }

但现在我收到以下错误:

Error activating IUnitOfWork using self-binding of IUnitOfWork
No constructor was available to create an instance of the implementation type.

我有一个我想用来处理我的后台工作的课程,使用hangfire如下:

 public class EmailJob
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMailer _mailer;

    public EmailJob(IUnitOfWork unitOfWork, IMailer mailer)
    {
        _unitOfWork = unitOfWork;
        _notificationMailer = notificationMailer;
    }

     public void Execute()
    {
        // DO Stuff
    }

}

任何人都知道我做错了什么?文档还说明:

Services registered with InRequestScope() directive will be unavailable during job activation, you should re-register these services without this hint.

这是什么意思?我仍然希望确保每个http请求只使用一个实现dbContext的IUnitOfwork类。如果我删除InRequestScope,现在如何影响应用程序的其余部分?

1 个答案:

答案 0 :(得分:1)

我认为问题在于您将IUnitOfWork绑定到自身。 Niject需要一个具体的类来激活UnitOfWork之类的东西。

  kernel.Bind<IUnitOfWork>()
        .To<UnitOfWork()
        .InNamedOrBackgroundJobScope(context => context.Kernel.Components.GetAll<INinjectHttpApplicationPlugin>()
        .Select(c => c.GetRequestScope(context))
        .FirstOrDefault(s => s != null));