ApplicationInsights Telemetry exception in system automation - azure-application-insights

In a project we call Powershell scripts in C#.
using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
var pipeline = runspace.CreatePipeline();
..
pipeline.Invoke();
..
This works without any issues until ApplicationInsights Telemetry package is installed. Version 1.2.x had this issue so I upgrade to 2.0.0, but still the same exception.
Stacktrace below:
System.Management.Automation.CmdletInvocationException
The type initializer for
'Microsoft.WindowsAzure.Commands.Common.MetricHelper' threw an
exception. System.Management.Automation.CmdletInvocationException: The
type initializer for
'Microsoft.WindowsAzure.Commands.Common.MetricHelper' threw an
exception. ---> System.TypeInitializationException: The type
initializer for 'Microsoft.WindowsAzure.Commands.Common.MetricHelper'
threw an exception. ---> System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. --->
System.InvalidOperationException: Type
'Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule,
Microsoft.AI.DependencyCollector, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' does not implement the required
interface
Microsoft.ApplicationInsights.Extensibility.ITelemetryModule. at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.CreateInstance(Type
interfaceType, String typeName) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstance(XElement
definition, Type expectedType, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstances[T](XElement
definition, ICollection`1 instances) --- End of inner exception
stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object
target, Object[] arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstance(XElement
definition, Type expectedType, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadProperties(XElement
instanceDefinition, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstance(XElement
definition, Type expectedType, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.Initialize(TelemetryConfiguration
configuration) at
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.get_Active()
at Microsoft.ApplicationInsights.TelemetryClient..ctor() at
Microsoft.WindowsAzure.Commands.Common.MetricHelper..cctor() ---
End of inner exception stack trace --- at
Microsoft.WindowsAzure.Commands.Common.MetricHelper.GenerateSha256HashString(String
originInput) at
Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.InitializeQosEvent()
at
Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.BeginProcessing()
at
Microsoft.WindowsAzure.Commands.Utilities.Profile.SubscriptionCmdletBase.BeginProcessing()
at System.Management.Automation.Cmdlet.DoBeginProcessing() at
System.Management.Automation.CommandProcessorBase.DoBegin() --- End
of inner exception stack trace --- at
System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable
input)
For now I deinstalled the NuGet package for ApplicationInsights, because I don't know a solution. Perhaps it's a bug in ApplicationInsights?

Related

EF Core with SQLite on Mono: e_sqlite3 not found

We are using Entity Framework Core 2.2.4 together with an SQLite database targeting .NET Framework 4.7.2. Following Nuget packages were installed:
Microsoft.Data.Sqlite
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
On my development machine (Windows 10) everything works fine but when trying to run the application with Mono on our 32-bit Linux machine, the following exception occurs:
FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: The type
initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
---> System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.DllNotFoundException: e_sqlite3
at (wrapper managed-to-native)
SQLitePCL.SQLite3Provider_e_sqlite3+NativeMethods.sqlite3_libversion_number()
at SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number () [0x00000] in <61bb3ca1db9c41ea88f280f0b1600d58>:0
at SQLitePCL.raw.SetProvider (SQLitePCL.ISQLite3Provider imp) [0x00008] in <3d4b21fb9c764efbb11f6e3b02efff52>:0
at SQLitePCL.Batteries_V2.Init () [0x00005] in <f5d9c86a14864b5d99b8bdece1b8292c>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
--- End of inner exception stack trace ---
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00048] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
at Microsoft.Data.Sqlite.Utilities.BundleInitializer.Initialize () [0x0002f] in <b46e232ade014524baa458345f270c50>:0
at Microsoft.Data.Sqlite.SqliteConnection..cctor () [0x00000] in <b46e232ade014524baa458345f270c50>:0
--- End of inner exception stack trace ---
at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.CreateDbConnection () [0x00006] in <74192050a4d342039620dc7ef6678f71>:0
at Microsoft.EntityFrameworkCore.Internal.LazyRef`1[T].get_Value () [0x00008] in <adf771f92e754fe1bb85c5850cd0c16b>:0
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection () [0x00000] in <69f795dffc844780bfcfff4ff8415a92>:0
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in <69f795dffc844780bfcfff4ff8415a92>:0
at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in <74192050a4d342039620dc7ef6678f71>:0
at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Exists () [0x0000c] in <74192050a4d342039620dc7ef6678f71>:0
at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists () [0x0000b] in <69f795dffc844780bfcfff4ff8415a92>:0
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate (System.String targetMigration) [0x00012] in <69f795dffc844780bfcfff4ff8415a92>:0
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate (Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade databaseFacade) [0x00010] in <69f795dffc844780bfcfff4ff8415a92>:0
at TestEfCorePlusSqlite.Program.Main (System.String[] args) [0x0000e] in <c4fad569c9a241ef887b5b2ddbc0225f>:0
Since the application is built with Any CPU configuration, x86 and x64 folders are created in bin/Debug, both containing an e_sqlite3.dll. I already tried to copy the x86 dll to bin/Debug but the error still occurred.
What I've tried so far:
installing Microsoft.EntityFrameworkCore.Sqlite.Core together with
SQLitePCLRaw.bundle_e_sqlite3 as suggested here
installing Microsoft.EntityFrameworkCore.Sqlite (or
Microsoft.Data.Sqlite or SQLitePCLRaw.bundle_green) as suggested here
different combinations of SQLitePCLRaw.* packages
What do I have to do to get EF Core and SQlite running on Mono?
After a refreshing weekend I took another glance at the problem. I found the official Mono documentation regarding DllNotFoundException and used MONO_LOG_LEVEL=debug mono YourApp.exe to find out which lib Mono is trying to load. It was /usr/lib/libe_sqlite3.so which was not available on my system. All I did was to copy the available /usr/lib/libsqlite3.so and rename it to libe_sqlite3.so. I'm not sure if this is the preferred way but my application works.

How can I specify the ASP.NET probing path for automatic C++/CLI appdomains?

I have a C++/CLI DLL that needs to run in the context of an ASP.NET WebApi action.
The action is affected by an ActionFilter that uses log4net's LogicalThreadContext to set a property containing a request ID; this works nicely to write the request ID into the log entries.
The problem is that ASP.NET seems to be creating an appdomain when it's time to load the class from the C++/CLI dll. (I can't seem to find any documentation on how that works; I'd love to find some.) When the appdomain plumbing tries to deserialize everything, it chokes because it can't find log4net.dll (see stack trace below).
Fusion logs show that it's looking in C:\Windows\System32\inetsrv, which is incorrect... I would expect it to look in the probing path or along the %PATH% environment variable.
A few data points:
log4net.dll is available in the web app's bin directory and works fine for everything else I'm using it for.
The C++/CLI code has no dependencies on log4net.
If I comment out my calls to log4net.LogicalThreadContext.Properties[...], everything works fine.
If I copy log4net.dll from my bin folder to C:\Windows\system32\inetsrv, everything works fine.
The web.config file specifies the probing path with a <probing privatePath="bin"/> element.
My Application_Start method in global.asax.cs prepends the web app's bin directory to the %PATH% environment variable:
var currentPathEnvVar = Environment.GetEnvironmentVariable("PATH");
var binPath = Path.Combine(Server.MapPath("~") ?? String.Empty, "bin");
_log.DebugFormat("Prepending paths to PATH: [{0}]", binPath);
Environment.SetEnvironmentVariable("PATH", String.Concat(binPath, Path.PathSeparator, currentPathEnvVar));
The log shows that the %PATH% is getting prepended correctly:
2015-06-05 17:07:48,816 1 DEBUG MyNamespace.WebApiApplication (null) Prepending paths to PATH: [C:\Program Files\MyCompany\MyApp\web\bin]
So how do I get the appdomain that ASP.NET creates to look in the right place to load assemblies?
Thanks.
Here's the stack trace that gets logged when all this goes down.
2015-06-05 17:08:41,148 23 ERROR MyNamespace.MyController (null) Controller action failed
System.TypeInitializationException: The type initializer for '<Module>' threw an exception. ---> <CrtImplementationDetails>.ModuleLoadException: The C++ module failed to load while attempting to initialize the default appdomain.
---> System.Runtime.Serialization.SerializationException: Unable to find assembly 'log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
Server stack trace:
at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.FixupForNewAppDomain()
at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoDispatch(Byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, SmuggledMethodReturnMessage& smuggledMrm)
at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoTransitionDispatchCallback(Object[] args)
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 System.AppDomain.IsDefaultAppDomain()
at <CrtImplementationDetails>.GetDefaultDomain() in f:\dd\vctools\crt\crtw32\h\minternal.h:line 367
at <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr function, Void* cookie) in f:\dd\vctools\crt\crtw32\h\minternal.h:line 401
at <CrtImplementationDetails>.DefaultDomain.Initialize() in f:\dd\vctools\crt\crtw32\msilcrt\mstartup.cpp:line 278
at <CrtImplementationDetails>.LanguageSupport.InitializeDefaultAppDomain(LanguageSupport* ) in f:\dd\vctools\crt\crtw32\msilcrt\mstartup.cpp:line 343
at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* ) in f:\dd\vctools\crt\crtw32\msilcrt\mstartup.cpp:line 546
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* ) in f:\dd\vctools\crt\crtw32\msilcrt\mstartup.cpp:line 703
--- End of inner exception stack trace ---
at <CrtImplementationDetails>.ThrowModuleLoadException(String errorMessage, Exception innerException) in f:\dd\vctools\crt\crtw32\h\minternal.h:line 194
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* ) in f:\dd\vctools\crt\crtw32\msilcrt\mstartup.cpp:line 713
at .cctor() in f:\dd\vctools\crt\crtw32\msilcrt\mstartup.cpp:line 754
--- End of inner exception stack trace ---
at MyNamespace.MyController.MyAction(String foo, Int64 bar, String baz)
This helped me to resolve similar issue:
https://blogs.msdn.microsoft.com/jorman/2007/08/31/loading-c-assemblies-in-asp-net/
Faced option 2.a and proposed solution worked fine:
protected void Application_Start(object sender, EventArgs e){
String _path = String.Concat(System.Environment.GetEnvironmentVariable("PATH"), ";",
System.AppDomain.CurrentDomain.RelativeSearchPath);
System.Environment.SetEnvironmentVariable("PATH", _path, EnvironmentVariableTarget.Process); }

Having a hard time tracking down a process that is crashing my app pool

So I have an app that keeps crashing out and it's not leaving any application logs. When I finally went and looked in the event viewer for that server (a server 2003 box), I found this error (The even source was ASP.NET 4.0.30319.0)
An unhandled exception occurred and the process was terminated.
Application ID: /LM/W3SVC/2053196604/Root
Process ID: 24428
Exception: System.IO.FileLoadException
Message: Could not load file or assembly
'Microsoft.Practices.EnterpriseLibrary.Validation, Version=5.0.505.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
StackTrace: Server stack trace: at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, Boolean reflectionOnly,
StackCrawlMarkHandle stackMark, Boolean loadTypeFromPartialName,
ObjectHandleOnStack type) at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, Boolean reflectionOnly,
StackCrawlMark& stackMark, Boolean loadTypeFromPartialName) at
System.RuntimeType.GetType(String typeName, Boolean throwOnError,
Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.AddValidationExtension()
at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator..ctor(IUnityContainer
container) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.CreateDefaultContainer(IConfigurationSource
configurationSource) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.SetCurrentContainerIfNotSet()
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer()
at Apriva.WebApi.Shared.Logging.DefaultLogWriter.Log(Object message,
TraceEventType severity, LogEntry& entry, String category, HttpContext
context) at
Apriva.WebApi.Shared.Logging.DefaultLogWriter.Info(Object message,
String category, HttpContext context) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Int32 methodPtr, Boolean
fExecuteInContext, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message
reqMsg, Boolean bProxyCase) at
System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed,
MessageData& msgData) at
Apriva.WebApi.Shared.Logging.Logger.LogDelegate.EndInvoke(IAsyncResult
result) at
Apriva.WebApi.Shared.Logging.Logger.LogAsyncComplete(IAsyncResult ar)
at
System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(IMessage
msg) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
For more information, see Help and Support Center at
When I check the processes in the task manager, this PID isn't present. I figure it's because it is a w3wp process. So I go to command prompt and run iisapp.vbs and it returns a single process with a different PID.
The error seems to imply that there is a config reference to a different version of the enterprise library for validation when the version that was found was v5.0.505.0 and while my projects have plenty of references to the enterprise library, none refer to the validation package.
So my question is -- does anyone have any insight into where I should look next? I was trying to use the PID to at least see which application was causing the error, but that doesn't seem to be getting me anywhere.
Analysis:
From stack trace its clear that reference chain is:
Apriva.WebApi.Shared.Logging.DefaultLogWriter => Microsoft.Practices.EnterpriseLibrary.Logging.Logger => Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer => Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.
Method "AddValidationExtension" of type Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator needs type from 'Microsoft.Practices.EnterpriseLibrary.Validation assembly with signature
Possible steps find out root cause:
Open solution in visual studio.
Go to Edit Menu-> Find and Replace->Find in Files
Search for Microsoft.Practices.EnterpriseLibrary.Validation with Find options->Look at these file types -> *.csproj You will get list of project referencing this assembly.
Open all those project files in notepad and find out which one has different assembly signature than Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
Most probably you should get culprit with above steps.
I will also recommend to check assembly cache and check signature of Microsoft.Practices.EnterpriseLibrary.Validation assembly and if it matches Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

Invalid IL code in System.Drawing.ColorConverter:.ctor (): method body is empty

I am Japanese developer,so English is a strange sorry. I am deploying an asp.net web project to a Mono linux box. I had the skeleton working pretty nice, but when I started Building in , I got the error you see above.
I've set the dll to copy local and added it to the bin_System.Drawing.dll and bin_System.Drowing.Design.dll folder, with no success.
It seems like I'm missing something simple. Any guesses what it is?
Server Error in '/' Application
Invalid IL code in System.Drawing.ColorConverter:.ctor (): method body is empty.
Description: HTTP 500. Error processing request.
Stack Trace:
System.InvalidProgramException: Invalid IL code in System.Drawing.ColorConverter:.ctor (): method body is empty.
at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
at System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0

Ninject ASP.NET extension throwing TypeLoadException

I'm trying to use Ninject 3 in an ASP.NET webforms application. We've been using it without the Ninject.Web extension for a while by creating a new injection kernel everywhere we needed one. It didn't occur to me until now that that's not the right way to do things. I wrote a little test application that is successfully using Ninject.Web, but when I tried to do the same thing in our real application, I'm receiving a TypeLoadException as soon as the page loads. It doesn't even make it into my code where I can set a breakpoint. Here's the exception and stack trace:
Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.
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
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.
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
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken,
IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs,
Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module,
Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext,
RuntimeTypeHandle[] methodInstantiationContext) +525
System.ModuleHandle.ResolveTypeHandle(Int32 typeToken,
RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[]
methodInstantiationContext) +19
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken,
Type[] genericTypeArguments, Type[] genericMethodArguments) +315
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord
caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly,
RuntimeModule decoratedModule, MetadataToken decoratedToken,
RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[]
attributes, IList derivedAttributes, RuntimeType& attributeType,
IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean&
isVarArg) +208
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule
decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount,
RuntimeType attributeFilterType, Boolean mustBeInheritable, IList
derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +1171
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly
assembly, RuntimeType caType) +146
WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly
assembly) +114
WebActivator.ActivationManager.RunActivationMethods() +286
WebActivator.ActivationManager.RunPreStartMethods() +38
WebActivator.ActivationManager.Run() +56
[InvalidOperationException: The pre-application start initialization
method Run on type WebActivator.ActivationManager threw an exception
with the following error message: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1
methods) +11567502
System.Web.Compilation.BuildManager.CallPreStartInitMethods() +465
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
appManager, IApplicationHost appHost, IConfigMapPathFactory
configMapPathFactory, HostingEnvironmentParameters hostingParameters,
PolicyLevel policyLevel, Exception appDomainCreationException) +1167
[HttpException (0x80004005): The pre-application start initialization
method Run on type WebActivator.ActivationManager threw an exception
with the following error message: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+141 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +4813333
None of my searching has turned up anything terribly helpful, but the main avenue I've explored is a potential conflict between the version of .NET that Ninject was built against and the version that I'm actually running. I've never installed .NET 4.5 on my system, so I'm certain that I'm building against 4.0. I then built the most recent version of Ninject (3.0.2) and the extensions from source to be sure that it's using 4.0 as well. I also tried adding all the libraries that I'm using in the real app to my test app to see if there's a conflict but that didn't turn up anything. (However, I didn't go so far as to put in code that exercises them. I don't know if that would change anything.)
Has anyone seen this kind of problem before or have any ideas that I can try? Is there more info I can provide that would be helpful?
Alternatively, is there some other way I can use Ninject in an ASP.NET application instead of the ninject.web extension? Would wrapping the Ninject kernel up in a singleton work just as well?

Resources