在 .NET Core 控制台应用程序中使用 Ninject

Using Ninject in .NET Core Console App

我正在尝试将我的代码从在 .NET Framework 4.6.1 上运行的 Webjobs 项目迁移到新的 .NET Core 2.0 控制台项目。我在这里遇到一些错误:

class Program
{
   // Here I'm getting IKernel is obsolete. Use IKernelConfiguration and IReadOnlyKernel message.
   // Also a message that reads: StandardKerynel is obsolete. Use StandardKernelConfiguration and StandardReadOnlyKernel 
   static readonly IKernel Kernel = new StandardKernel();
   static JobHostConfiguration config;

   static void Main(string[] args)
   {
      Environment.SetEnvironmentVariable("AzureWebJobsDashboard", "connection");
      Environment.SetEnvironmentVariable("AzureWebJobsStorage", "storage connection");

      BootStrapIoc();

      config = new JobHostConfiguration();

      if (config.IsDevelopment)
      {
          config.UseDevelopmentSettings();
      }

      var host = new JobHost(config);
      host.RunAndBlock();
   }

   private static void BootStrapIoc()
   {
      // Also getting an error here that reads: Argument 1: Cannot convert System.Reflection.Assembly to System.Collections.Generic.IEnumerable<Ninject.Modules.NinjectModule>
      Kernel.Load(Assembly.GetExecutingAssembly());
      config = new JobHostConfiguration
      {
         JobActivator = new BrmJobActivator(Kernel)
      };
   }
}

我的 BrmJobActivator 代码也出现错误:

public class BrmJobActivator : IJobActivator
{
   private readonly IKernel _container;

   public BrmJobActivator(IKernel container)
   {
       _container = container;
   }

   public T CreateInstance<T>()
   {
       return _container.Get<T>();
   }
}

更新: 这是安装 Ninject 包 3.2.2 后我的项目中 NuGet 包下的警告消息:

Also getting an error here that reads: Argument 1: Cannot convert System.Reflection.Assembly to System.Collections.Generic.IEnumerable

Ninject 的最新预发布版本有一些变化。请安装最新的稳定版 3.2.2。

我在我这边测试了你的代码。将 Ninject 版本更新到 3.2.2 后,代码运行正常。

Ninject 3.3.0 于 2017 年 9 月 26 日发布,现在针对 .NET Standard 2.0,因此也可以在 .NET Core 2.0 上运行。更新到 3.3.0 将修复警告。