Hangfire with Ninject

本文关键字:Ninject with Hangfire | 更新日期: 2023-09-27 17:52:36

我正在尝试使用Hangfire与Ninject。

这是我的问题,我的项目是这样布局的:

.Sln
    |- Core
    |- Web

现在在Core中是Hangfire方法:

public class Scheduler
{
    public void HangfireIoc()
    {
        BackgroundJob.Enqueue<MovieSaver>(x => x.SaveMovies());
    }
}

MovieSaver类在(Core):

public class MovieSaver
{
    public IMovieApi Api { get; set; }
    public MovieSaver(IMovieApi api)
    {
        Api = api;
    }
   //Other methods
}

Startup.cs (In Web)

public void Configuration(IAppBuilder app)
{
  var kernal = new StandardKernel();
  GlobalConfiguration.Configuration.UseNinjectActivator(kernal);
  app.UseHangfireDashboard();
  app.UseHangfireServer();
}

我有一个绑定类在Core为Ninject:

public class Bindings : NinjectModule
{
    public override void Load()
    {
        Bind<IMovieApi>().To<MovieApi>();
    }
} 

但似乎当Hangfire开始我得到的工作时:

Ninject.ActivationException
Error activating IMovieApi No matching bindings are available, and the type is not self-bindable.
 Activation path: 2) Injection of dependency IMovieApi into parameter api of constructor of type MovieSaver 
1) Request for MovieSaver Suggestions: 1) Ensure that you have defined a binding for IMovieApi. 
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 
3) Ensure you have not accidentally created more than one kernel. 
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 
5) If you are using automatic module loading, ensure the search path and filters are correct.

我是Ninject和IoC容器的新手。

有人能帮忙吗?

Hangfire with Ninject

Bindings模块未加载。尝试添加

kernel.Load<Bindings>();

到Startup.cs的Configuration方法。

还可以通过调用

来加载程序集中的所有Module
kernel.Load(someAssembly);
例如:

kernel.Load(typeof(Startup).Assembly);

New Ninject.Web.Common.Bootstrapper().Kernel:

public void Configuration(IAppBuilder app)
    {            
        ConfigureAuth(app);
        GlobalConfiguration.Configuration
            .UseSqlServerStorage("ConnectString");
        GlobalConfiguration.Configuration.UseNinjectActivator(new Ninject.Web.Common.Bootstrapper().Kernel);

        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }