Using Ninject in .NET Core Console App

2019-08-20 22:32发布

I'm trying to migrate my code from a Webjobs project runing on .NET Framework 4.6.1 to a new .NET Core 2.0 Console project. I'm getting errors some errors here:

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)
      };
   }
}

I'm also getting errors in my BrmJobActivator code:

public class BrmJobActivator : IJobActivator
{
   private readonly IKernel _container;

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

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

UPDATE: This is the warning message under NuGet packages in my project after installing Ninject package 3.2.2: enter image description here

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-20 23:25

Ninject 3.3.0 was released September 26th 2017 and now targets .NET Standard 2.0 and thus also runs on .NET Core 2.0. Updating to 3.3.0 will fix the warning.

查看更多
别忘想泡老子
3楼-- · 2019-08-20 23:32

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

There are some changes in the latest prerelease version of Ninject. Please install the latest stable 3.2.2 version instead.

enter image description here

I tested your code on my side. After updated the Ninject version to 3.2.2, the code worked fine.

查看更多
登录 后发表回答