Ninject ToFactory works in Resharper unit tests, but not NCrunch - visual-studio-2010

I'm using Ninject.Extensions.Factory with Ninject 3 to create a factory, which creates different types of IFoo based on the string provided to the factory. I've got a passing unit test, but oddly, only in the Resharper test runner. In the NCrunch test runner it fails. Is this a NCrunch config issue, or do I need to change the code?
The interface:
public interface IFooFactory
{
IFoo CreateFoo(string name);
}
The Ninject bindings:
kernel.Bind<IFooFactory>().ToFactory(() => new UseFirstParameterAsNameInstanceProvider());
kernel.Bind<IFoo>().To<BarFoo>().Named("Bar");
The test:
[Test]
public void CanCreateFooTest()
{
var factory = (IFooFactory) Kernel.GetService(typeof(IFooFactory));
var bar = factory.CreateFoo("Bar");
Assert.AreEqual(typeof(BarFoo), bar.GetType());
}
And the NCrunch exception:
System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> Ninject.ActivationException : Error activating IInterceptor using conditional implicit self-binding of IInterceptor
Provider returned null.
Activation path:
2) Injection of dependency IInterceptor into parameter of constructor of type IFooFactoryProxy
1) Request for IFooFactory
Suggestions:
1) Ensure that the provider handles creation requests properly.
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerable.ToArraySlow(IEnumerable series, Type elementType) in c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerable.cs:line 29
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:line 149
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 114
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 96
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 95
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.Single[TSource](IEnumerable`1 source)
at Ninject.KernelBase.System.IServiceProvider.GetService(Type service) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 553
at FooProject.Tests.CanCreateFooTest() in C:\Projects\FooProject ...
--ActivationException
at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 165
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.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)

Go into the NCrunch configuration for the unit test library and set Copy referenced assemblies to workspace to True.

Here the code that works with NCrunch:
var kernel = new StandardKernel();
kernel.Bind<IFooFactory>().ToFactory(() => new UseFirstParameterAsNameInstanceProvider());
kernel.Bind<IFoo>().To<BarFoo>().Named("Bar");
kernel.Load<FuncModule>();
var factory = kernel.Get<IFooFactory>();
var bar = factory.CreateFoo("Bar");
Assert.Equal(typeof(BarFoo), bar.GetType());
UPDATE
This works great, and sorts out NCrunch. However, Resharper complains that it has been loaded twice. The workaround:
#if NCRUNCH
Kernel.Load<FuncModule>();
#endif

The FuncModule is not loaded when running with that TestRunner. This happens in case the extension is not copied to the startup directory of the executed process.
I don't NCrunch. So I can't tell you what it is doing. But most likely it copies the assemblies in a different way than the R# test runner. You could load the extensions manually but this feels like a hack.

I have been using harriyott's suggestion for a year or so. But then this problem happend on our TFS-Buildserver, too. So now I avoid Ninject automatically loading of all Extensions and Load them manually. This avoids the #if, #endif and the same code will run on Resharper and NCrunch:
var kernel = new StandardKernel(new NinjectSettings { LoadExtensions = false});
kernel.Load<FuncModule>();
the rest is unchanged:
kernel.Bind<IFooFactory>().ToFactory(() => new UseFirstParameterAsNameInstanceProvider());
kernel.Bind<IFoo>().To<BarFoo>().Named("Bar");
var factory = kernel.Get<IFooFactory>();
var bar = factory.CreateFoo("Bar");
Assert.Equal(typeof(BarFoo), bar.GetType());

Related

Server Error in '/' Application after build solution in Visual Studio

Im trying to sync my projects with Sitecore database but when I build the solution provided by Sitecore Learning (Clothing Company), my website is not loaded and an error appears. It was working fine before I try to build it.
`Server Error in '/' Application.
Could not load type 'Sitecore.HealthCheck.DependencyInjection.HealthChecksBuilder' from assembly 'Sitecore.Kernel, Version=13.0.0.0, Culture=neutral, PublicKeyToken=null'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.TypeLoadException: Could not load type 'Sitecore.HealthCheck.DependencyInjection.HealthChecksBuilder' from assembly 'Sitecore.Kernel, Version=13.0.0.0, Culture=neutral, PublicKeyToken=null'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[TypeLoadException: Could not load type 'Sitecore.HealthCheck.DependencyInjection.HealthChecksBuilder' from assembly 'Sitecore.Kernel, Version=13.0.0.0, Culture=neutral, PublicKeyToken=null'.]
Sitecore.ContentSearch.SolrProvider.DependencyInjection.ContentSearchServicesConfigurator.AddContentSearchHealthChecks(IServiceCollection serviceCollection) +0
Sitecore.DependencyInjection.BaseServicesConfiguratorFactory.Configure(IServiceCollection serviceCollection) +171
Sitecore.DependencyInjection.BaseServicesConfiguratorFactory.Configure(IServiceCollection serviceCollection) +171
Sitecore.DependencyInjection.BaseServiceProviderBuilder.ConfigureServiceCollection() +142
Sitecore.DependencyInjection.ServiceLocator.ConfigureServiceProvider() +225
Sitecore.DependencyInjection.ServiceLocator.get_ServiceProvider() +513
Sitecore.DependencyInjection.SitecorePerRequestScopeModule..ctor() +13
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +142
System.Activator.CreateInstance(Type type, Boolean nonPublic) +107
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1476
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +186
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +28
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +80
System.Web.HttpApplication.BuildIntegratedModuleCollection(List`1 moduleList) +234
System.Web.HttpApplication.GetModuleCollection(IntPtr appContext) +1153
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +139
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +168
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +277
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +369
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +724`
Looking at error, it seems the Sitecore.Kernel.dll is getting replaced with different version in your website bin or your web.config file is getting replaced which might be having different assembly binding version info for Sitecore.kernel.dll.
I would suggest, check the Sitecore.kernel.dll version from your original website bin, in dotpeek.
Update Sitecore.kernel.dll of this version in your project solution via Nuget manager or update your DLL in your managed lib folder or DLL location folder.
Keep the assembly binding info in solution web.config as same as in the original web.config if you have.
If the DLL version is same both the place already, then load the Sitecore.kernel.dll in dotpeek, check for class Sitecore.HealthCheck.DependencyInjection.HealthChecksBuilder if there or not. If not, then some config file is having an entry for this class. Search word HealthChecksBuilder in App_config folder files, and comment the setting where you find and see if the site is up or not.
Then VS publish hope the issue gets resolved.

Exchange Server 2016: Server Error in '/ecp' Application

I am getting error in the ECP of Exchange Server 2016 while the OWA is working fine. The ECP login page opens but after login we get following error. This issue has been for around a week and we have not made any progress. Please assist if anyone has face similar error and resolved the issue.
Server Error in '/ecp' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:
1. Add a "Debug=true" directive at the top of the file that generated the error. Example:
<%# Page Language="C#" Debug="true" %>
or:
2) Add the following section to the configuration file of your application:
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.
Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Exchange.Management.ControlPanel.Global..cctor() +119
[TypeInitializationException: The type initializer for 'Microsoft.Exchange.Management.ControlPanel.Global' threw an exception.]
ASP.global_asax..ctor() +28
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +139
System.Activator.CreateInstance(Type type, Boolean nonPublic) +105
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1431
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +184
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +27
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +79
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +178
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +341
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +523
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +107
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +688
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3770.0

NUnit runner compilation failed error with ReSharper and NUNIT

I have a project with 100s of tests. Some of them run fine, others just say Inconclusive - Test not run. These tests have run fine in the past. Also, I am getting the below error that I am sure is related. These tests run fine if I run them one by one.
2016.12.19 16:33:25.658 ERROR JetBrains.ReSharper.UnitTestRunner.nUnit.CodeDom.CompileException: NUnit runner compilation failed
(0:0) Error generating Win32 resource: The system cannot find the path specified.
Server stack trace:
at JetBrains.ReSharper.UnitTestRunner.nUnit.CodeDom.RunnerTypeCompiler.AssertCompilationResultsHaveNoErrors(CompilerResults compilerResults)
at JetBrains.ReSharper.UnitTestRunner.nUnit.CodeDom.RunnerTypeCompiler.CompileIntoAssembly(String outputPath, Assembly resourceAssembly, String[] resourcesToCompile, String[] assembliesToReference)
at JetBrains.ReSharper.UnitTestRunner.nUnit30.DelegatingTestRunner.GetRunner(String nUnitInstallDir, TaskExecutorConfiguration configuration, SimpleLogger logger) in c:\Build Agent\work\10282fe47e6c6213\Psi.Features\UnitTesting\nUnit\Runner30\Src\DelegatingTestRunner.cs:line 70
at JetBrains.ReSharper.UnitTestRunner.nUnit30.DelegatingTestRunner.RunTests(IRemoteTaskServer server, List`1 assemblies, Dictionary`2 tests, Dictionary`2 fixtures, List`1 explicitly, Boolean useAddins, String nUnitInstallDir, TaskExecutorConfiguration configuration, SimpleLogger logger) in c:\Build Agent\work\10282fe47e6c6213\Psi.Features\UnitTesting\nUnit\Runner30\Src\DelegatingTestRunner.cs:line 43
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at JetBrains.ReSharper.UnitTestRunner.nUnit.INUnitRunner.RunTests(IRemoteTaskServer server, List`1 assemblies, Dictionary`2 tests, Dictionary`2 fixtures, List`1 explicitly, Boolean useAddins, String nUnitInstallDir, TaskExecutorConfiguration configuration, SimpleLogger logger)
at JetBrains.ReSharper.UnitTestRunner.nUnit.NUnitTaskRunner.Run(String nUnitInstallDir, String assmbl, Boolean useAddins)
at JetBrains.ReSharper.UnitTestRunner.nUnit.NUnitTaskRunner.RunTestsInAssemblies(List`1 assemblies, NUnitTestAssemblySetTask assemblySetTask, Boolean useAddins, NUnitVersion nUnitVersion)
at JetBrains.ReSharper.UnitTestRunner.nUnit.NUnitTaskRunner.ExecuteRecursive(TaskExecutionNode node)
at JetBrains.ReSharper.TaskRunnerFramework.StartupTaskRunnerHost.Execute(TaskExecutionNode node)
at JetBrains.ReSharper.TaskRunnerFramework.StartupTaskRunnerHost.ExecuteNodes(IEnumerable`1 nodes)
at JetBrains.ReSharper.TaskRunnerFramework.TasksPacketHandler.ThreadProc(TaskRunnerProxy proxy, IEnumerable`1 packets, AssemblyLoader loader)
This is a bug with the latest version ("2016.3") of Resharper. More details here... https://youtrack.jetbrains.com/issue/RSRP-462284
The issue occurs when you have multiple test assemblies.

RavenDb, Cannot access file, the file is locked or in use

This is exception is totally make my life a pain right now.. Don't rightly know whats changed but the database is in the App_Data folder of a MVC3 site. The website is hosted in IIS 7.5 proper as the Default Web Site.
Any tips for resolution would be welcome.
EDIT.. The problem is probably more or less related to my controller code not cleaning up after an exception is being thrown, thus not calling dispose on the document session
Line 30: instance = new EmbeddableDocumentStore { ConnectionStringName = "RavenDB" };
Line 31: instance.Conventions.IdentityPartsSeparator = "-";
Line 32: instance.Initialize();
[EsentFileAccessDeniedException: Cannot access file, the file is locked or in use]
Microsoft.Isam.Esent.Interop.Api.Check(Int32 err) in C:\Work\ravendb\SharedLibs\Sources\managedesent-61618\EsentInterop\Api.cs:2739
Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance) in C:\Work\ravendb\SharedLibs\Sources\managedesent-61618\EsentInterop\Api.cs:131
Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator) in c:\Builds\RavenDB-Stable\Raven.Storage.Esent\TransactionalStorage.cs:207
[InvalidOperationException: Could not open transactional storage: C:\code\BE\Com.BuyEfficient\Com.BuyEfficient.Web\App_Data\ravendata\Data]
Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator) in c:\Builds\RavenDB-Stable\Raven.Storage.Esent\TransactionalStorage.cs:220
Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration) in c:\Builds\RavenDB-Stable\Raven.Database\DocumentDatabase.cs:156
Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal() in c:\Builds\RavenDB-Stable\Raven.Client.Embedded\EmbeddableDocumentStore.cs:143
Raven.Client.Document.DocumentStore.Initialize() in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Document\DocumentStore.cs:483
Com.BuyEfficient.Web.Infrastructure.DataDocumentStore.Initialize() in C:\code\BE\Com.BuyEfficient\Com.BuyEfficient.Web\Infrastructure\DataDocumentStore.cs:32
Com.BuyEfficient.Web.App_Start.Services.PreStart() in C:\code\BE\Com.BuyEfficient\Com.BuyEfficient.Web\App_Start\Services.cs:25
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +72
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +335
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +28
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
WebActivator.BaseActivationMethodAttribute.InvokeMethod() +221
WebActivator.ActivationManager.RunActivationMethods() +491
WebActivator.ActivationManager.RunPreStartMethods() +28
WebActivator.ActivationManager.Run() +55
[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +423
System.Web.Compilation.BuildManager.CallPreStartInitMethods() +306
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +677
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090044
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256
Spaten, you need to make sure that you handle DocumentStore and DocumentSession lifecycle management properly. You should create the DocumentStore as a singleton on application start and you should open and dispose session on begin and end request. I suggest writing your own handlers for OnBeginRequest and OnEndRequest.
Please take a look at the official sample application, RaccoonBlog, to see how this works.

NLog Failing on Release Mode in IIS7

EDIT: As Kirk Woll correctly pointed out, the issue is NLog, not with NInject. So let me rephrase the issue:
EDIT2: Now that I knew it was NLog + an IoC problem, I found the solution at ASP.NET MVC2 + Ninject + NLog (+ shared hosting?) = NullReferenceException
I have a project that is using NInject to inject an NLogger class via an ILogger interface into all of my controllers. Steven, to answer your question to keep my web.config clean, I have used an NLog.Config file to separate out that configuration.
When I target IIS7 in Debug mode, the code works correctly, but in Release Mode I get the below stack trace.
If anyone has any idea why in Debug Mode the code would work, and why in Release it wouldn't, it'd be much appreciated. I've also included my NLog Config File below.
<?xml version="1.0"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
<target name="file" xsi:type="File" fileName="${basedir}/App_Data//Logs/site.log"
layout="${date}: ${message}" />
<target name="eventlog" xsi:type="EventLog"
source="Template"
log="Application"
layout="${date}: ${message} ${stacktrace}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="file" />
<logger name="*" minlevel="Fatal" writeTo="eventlog" />
</rules>
</nlog>
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
NLog.LogManager.GetCurrentClassLogger() +84
DynamicInjectorc5f536e7a4564738b2e779e62f9c20c7(Object[] ) +40
Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:81
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Context.cs:157
Ninject.KernelBase.<Resolve>b__7(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\KernelBase.cs:375
System.Linq.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x) +32
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4222965
Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Planning\Targets\Target.cs:179
Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Planning\Targets\Target.cs:147
Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:97
Ninject.Activation.Providers.<>c__DisplayClass2.<Create>b__1(ITarget target) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:81
System.Linq.WhereSelectArrayIterator`2.MoveNext() +85
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +78
Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:81
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\Activation\Context.cs:157
Ninject.KernelBase.<Resolve>b__7(IContext context) in c:\Projects\Ninject\Maintenance2.2\ninject\src\Ninject\KernelBase.cs:375
System.Linq.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x) +32
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4222965
Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\Maintenance2.2\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:56
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +51
[InvalidOperationException: An error occurred when trying to create a controller of type 'BossP.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963444
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Well, I spend 2 nights on investigation and solving the issue. Initially I thought that problem related to NLog logging framework so I switched to Log4Net instead. That was easy because I used Ninject.Extensions.Logging. But that didn't helped.
Then I updated to prerelease version of Ninject and exception message became more clear: "Can not determine current class for DynamicInjectorb709a37f02d44e5a8615c5fde4e0746d".
Finally some googling pointed me to the following discussion: https://groups.google.com/forum/#!msg/ninject/V_bS0ykJxAA/IBnsGVnL50UJ
Solution: "Try use reflection instead by creating a kernel with a NinjectSettings instance that has UseReflectionBasedInjection set to true"
I have experienced a similar problem.
My (simplistic) solution:
replace these lines
private Logger Logger = LogManager.GetCurrentClassLogger();
by this line
private static Logger Logger = LogManager.GetCurrentClassLogger();
The "readonly" keyword is optional.

Resources