加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

依赖注入 – 使用InRequestScope与Ninject进行Hangfire

发布时间:2020-12-14 04:50:20 所属栏目:百科 来源:网络整理
导读:我已将Hangfire.Ninject包安装到ASP MVC 5应用程序,以便我可以运行一些后台作业. 我已经阅读了文档,但我对如何实现它感到困惑. 我现有的配置使用InRequestScope作为我的IUnitOfwork类,以确保每个HTTP请求只实例化一个实例,如下所示: private static void Re
我已将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,现在如何影响应用程序的其余部分?

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读