【问题标题】:Hangfire with Ninject using InRequestScope使用 InRequestScope 与 Ninject 进行 Hangfire
【发布时间】:2016-08-07 17:34:06
【问题描述】:

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

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

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

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

要按照文档使用 ninject 和 hangfire,我在 ninjectwebcommon.cs 类中更新了如下配置:

 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,这将如何影响应用程序的其余部分?

【问题讨论】:

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


    【解决方案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));
    

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 2011-10-18
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多