Question

I have a simple console app using Ninject, Ninject.Logging and Ninject.Extensions.NLog2 all build with latest nuget packages.

My App does the following

 _kernel = new StandardKernel();
 ILogger logger = _kernel.Get<ILogger>();

And I get a Null Reference exception from within StandardKernel when calling Get<ILogger>()

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.    
  Source=Ninject.Extensions.Logging
  StackTrace:
       at Ninject.Extensions.Logging.LoggerFactoryBase.GetLogger(IContext context) in     c:\Projects\Ninject\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerFactoryBase.cs:line 61
   at Ninject.Extensions.Logging.LoggerModuleBase.<Load>b__0(IContext context) in c:\Projects\Ninject\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerModuleBase.cs:line 26
   at Ninject.Activation.Providers.CallbackProvider`1.CreateInstance(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\CallbackProvider.cs:line 45
   at Ninject.Activation.Provider`1.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Provider.cs:line 38
   at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
   at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37

Is there any more config I need to go to get logging working?

Was it helpful?

Solution

You should not directly ask for an ILogger (although the error message could be a little bit nicer) but you should resolve an ILoggerFactory and from that you can ask for an ILogger

_kernel = new StandardKernel();
ILoggerFactory loggerFactory = _kernel.Get<ILoggerFactory>();
ILogger logger = loggerFactory.GetCurrentClassLogger();

See also the documentation Request a logger yourself section.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top