我已将 Hangfire.Ninject 包安装到 ASP MVC 5 应用程序中,以便我可以运行一些后台作业。
我已经阅读了文档,但我对如何实现它感到困惑。
我现有的配置对我的 IUnitOfwork 类使用 InRequestScope,以确保每个 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,这将如何影响应用程序的其余部分?