c# – Hangfire配置和Ninject配置

我有一个使用Ninject的MVC 5应用程序,我正在向其添加Hangfire。

当我添加了Ninject时,我使用了NinjectWebCommon nuget包,因为它的配置很简单。所以现在,Ninject通过NinjectWebCommon类进行配置,该类创建一个标准内核并添加绑定。

此外,我创建了一些在创建内核时加载的自定义模块

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

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

Ninject Web Common通过WebActivatorEx类注册

[assembly: WebActivatorEx.PreApplicationStartMethod( typeof( MyProject.Web.NinjectWebCommon ), "Start" )]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute( typeof( MyProject.Web.NinjectWebCommon ), "Stop" )]

现在的问题是关于如何使Hangfire看到Ninject配置。看看Hangfire.Ninject包,我可以阅读

The package provides an extension method for IGlobalConfiguration
interface:

var kernel = new StandardKernel();
GlobalConfiguration.Configuration.UseNinjectActivator(kernel);

现在我的问题是:

>由于IGlobalConfiguration接口,我应该在OWIN启动方法(其中已经放置了Hangfire配置)的情况下添加Hangfire Ninject配置。我应该如何获取当前的Ninject内核(NinjectWebCommon已配置的内核)?
>执行顺序怎么办?在OWIN启动之前还是之后WebActivator是否执行?
>如果我尝试执行两次配置会怎么样?

更一般来说,我如何在两者之间共享Ninject配置?

How should I get the current Ninject Kernel

看看Ninject.Web.Common.Bootstrapper的代码显示它存储一个单一的内核静态实例,并通过Kernel属性公开它。这意味着您可以在OWIN启动方法中执行此操作:

GlobalConfiguration.Configuration.UseNinjectActivator(
                                     new Ninject.Web.Common.Bootstrapper().Kernel);

并且您将拥有与NinjectWebCommon.RegisterServices中配置的任何绑定相同的IKernel实例

What about the order of execution? Is the WebActivatorEx executing before or after the OWIN startup?

之前。您可以通过在每个中设置断点来验证(如我所做)。 More info

More generally, how can I share the Ninject configuration between the two?

What happens if I try to execute the configuration twice?

内核配置是“组合​​根”。据这位专家的杰出专家马克·塞曼(Mark Seemann)说,那里有should only be one of these in the applicationit should be as close as possible to the application’s entry point.

http://stackoverflow.com/questions/30856995/hangfire-configuration-and-ninject-configuration

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – Hangfire配置和Ninject配置