Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions' on ASP.NET Core only on Windows PC - asp.net-core

This ASP.NET Core 2.1 Project runs fine on my Mac OS. However it throws this exception when I run it from Windows PC. I tried to run this from two Windows machines using the same version of .NET Core SDK.
I tried reinstalling .NET Core SDK 2.1.302, also tried upgrading to 2.1.401. Appreciate any help.
The error is
System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Used Nuget Packages in .csproj file
<PackageReference Include="HangFire" Version="1.6.19" />
<PackageReference Include="Hangfire.LiteDB" Version="0.1.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.1.1" />
<PackageReference Include="LiteDB" Version="4.1.4" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
Full stack trace
> dotnet run
Using launch settings from C:\Source\repos\src\Properties\launchSettings.json...
Application startup exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance[T]()
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
at Microsoft.Extensions.Options.OptionsManager`1.Get(String name)
at Microsoft.Extensions.Options.OptionsManager`1.get_Value()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.CreateServiceContext(IOptions`1 options, ILoggerFactory loggerFactory)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer..ctor(IOptions`1 options, ITransportFactory transportFactory, ILoggerFactory loggerFactory)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6]
Application startup exception
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance[T]()
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
at Microsoft.Extensions.Options.OptionsManager`1.Get(String name)
at Microsoft.Extensions.Options.OptionsManager`1.get_Value()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.CreateServiceContext(IOptions`1 options, ILoggerFactory loggerFactory)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer..ctor(IOptions`1 options, ITransportFactory transportFactory, ILoggerFactory loggerFactory)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance[T]()
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
at Microsoft.Extensions.Options.OptionsManager`1.Get(String name)
at Microsoft.Extensions.Options.OptionsManager`1.get_Value()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.CreateServiceContext(IOptions`1 options, ILoggerFactory loggerFactory)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer..ctor(IOptions`1 options, ITransportFactory transportFactory, ILoggerFactory loggerFactory)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at JustALink.Program.Main(String[] args) in C:\Source\repos\src\Program.cs:line 10

This problem is a known issue in .NET Core 2.1.x that was fixed in .NET Core 2.1.5 and newer. See https://github.com/dotnet/core-setup/issues/4512.
If you are getting failures due to "System.IO.FileLoadException" after updating the .NET Core SDK, you are probably running into https://github.com/dotnet/core-setup/issues/4376.
The best fix is to upgrade to .NET Core 2.1.5 or newer.
If you can't upgrade, another workaround is to update the project to
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.3" />
The cause of this issue, as described in https://github.com/dotnet/core-setup/issues/4376, is unintentionally upgrading out of the shared framework. For example:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.1" />
Microsoft.AspNetCore.All 2.1.0 depends on Microsoft.AspNetCore.SignalR 1.0.0, but your project has upgrade to Microsoft.AspNetCore.SignalR 1.0.1. When you dotnet publish, you get Microsoft.AspNetCore.SignalR 1.0.1 AND ⚠️ its transitive dependencies in your publish folder. This is the publish trimming pitfall described in https://natemcmaster.com/blog/2018/08/29/netcore-primitives-2/.
This results in the following
+=================+===============================+================================+============================+
| AspNetCore.All | M.A.Connections.Abstractions | M.A.Connections.Abstractions | Which M.A.C.Abstractions |
| | (in shared framework) | (in publish dir) | should load |
+=================+===============================+================================+============================+
| 2.1.0 | 2.1.0 | 2.1.1 | publish dir |
+-----------------+-------------------------------+--------------------------------+----------------------------+
| 2.1.3 | 2.1.3 | 2.1.1 | shared framework* |
+-----------------+-------------------------------+--------------------------------+----------------------------+
* This is bug, and https://github.com/dotnet/core-setup/issues/4512 tracks getting a fix in a future 2.1.x update.

If you don't have Microsoft.AspNetCore.All, you can use Microsoft.AspNetCore.App and set its version to 2.1.3. They are quite the same:
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.3"/>

I solved the problem by upgrading Microsoft.AspNetCore.All from 2.1.0 -> 2.1.3 (upgraded SDK to 2.1.401)
Still don't have a clue why this was working on Mac but not on Windows.

My Web API Core project file didn't contain Microsoft.AspNetCore.All. I manually added it to the item group and it fixed it for me.

You can add manually Connection.Abstractions dll
<PackageReference Include="Microsoft.AspNetCore.Connections.Abstractions" Version="2.1.3" />

Related

"Exception has been thrown by the target of an invocation" error when injecting Amazon S3 Service in ASP .Net Core constructor

I have an ASP .Net Core 2.2 Web API. In it, I have an endpoint where the front-end (Angular app) can send a file to the API, and the API in turn uploads this file to an Amazon S3 bucket (us-east-1 region).
This works perfectly while I'm debugging in Visual Studio, but when I publish to my server (Windows Server 2016) I get the following exception:
Error: Exception has been thrown by the target of an
invocation. at System.RuntimeMethodHandle.InvokeMethod(Object
target, Object[] arguments, Signature sig, Boolean constructor,
Boolean wrapExceptions) at
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Amazon.Extensions.NETCore.Setup.ClientFactory.CreateClient(Type
serviceInterfaceType, AWSCredentials credentials, ClientConfig config)
at
Amazon.Extensions.NETCore.Setup.ClientFactory.CreateServiceClient(ILogger
logger, Type serviceInterfaceType, AWSOptions options) at
Amazon.Extensions.NETCore.Setup.ClientFactory.CreateServiceClient(IServiceProvider
provider) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite
factoryCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite
scopedCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite
singletonCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite
constructorCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite
scopedCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite
singletonCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.
b__0(ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type
serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type
serviceType) at
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] ) at
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.
b__0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.
g__CreateController|0(ControllerContext
controllerContext) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next,
Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext
httpContext) at
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext
httpContext) at
PropWorx.API.Middlewares.TenantIdentifier.Invoke(HttpContext
httpContext, SharedContext sharedContext) in
C:\Users\fabsr\source\repos\PropWorx.API\PropWorx.API\Middlewares\TenantIdentifier.cs:line
73 at
Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext
context) at
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext) at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider) at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext
context)
I've created the "credentials" file in the %UserProfile%.aws folder.
I've added the following two NuGet packages to the project:
AWSSDK.Extensions.NETCore.Setup
AWSSDK.S3
I have this in my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAWSService<IAmazonS3>();
services.AddSingleton<IS3Service, S3Service>();
}
S3Service.cs looks like this:
public class S3Service : IS3Service
{
private readonly IAmazonS3 _client;
public S3Service(IAmazonS3 client)
{
_client = client;
}
// Some methods to upload and delete objects... not important
}
I inject this service to one of my controllers:
public class FilesController : ControllerBase
{
private readonly IS3Service _s3Service;
public FilesController(IS3Service s3Service)
{
_s3Service = s3Service;
}
// Some actions to receive the file... not important
}
The error happens as soon as I call any action in this controller. In fact, the error appears to be happening when the S3Service is injected into the controller's constructor. If I remove the constructor injection, i.e.:
public class FilesController : ControllerBase
{
private readonly IS3Service _s3Service;
public FilesController()
{
}
// Some actions to receive the file... not important
}
The error goes away (but of course doesn't work properly)
Any ideas? Like I said, this works perfectly on my laptop while debugging in VS2017. But it doesn't work when published to the server. All other controllers in the API work fine. It appears to be a problem at the point of injecting the S3Service in the constructor...
I kept it simple. In my local machines, I was keeping the keys in the user-secrets and on the prod server I was keeping those in the IIS configuration file. and was just accessing these values from ConfigurationManager. Basically it was using the new AmazonS3Client(string, string, string) syntax. Also I was using a farily older version of .net core there is a possibility that the issue was fixed. Check out this which seems working.
I changed my code to get IAmazonS3 insatance not through but directly instantiating it inside my IS3Serice method and it worked. Somehow the DI is not able to pick config values and that's why was not able to resolve the object.
You can get some information about this from here
I went through the actual documentation
https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html
and found following:
If you look at the Debug tab in your project's properties, you can see this file is set to Development. This works great for local testing because you can put your configuration in the appsettings.Development.json file, which is read-only during local testing. When you deploy an Amazon EC2 instance that has EnvironmentName set to Production, this file is ignored and the AWS SDK for .NET falls back to the IAM credentials and region configured for the Amazon EC2 instance.
So this could be the reason that your initial configurations didn't work as you were trying to use access keys on production.
Also have a look at following answer
How to set credentials on AWS SDK on NET Core?

Could not load file or assembly 'MvcSiteMapProvider

I added the provider via nuget console Install-Package MvcSiteMapProvider.MVC4.
The install looked good:
Successfully added 'MvcSiteMapProvider.MVC4 4.6.22' to XYZ.
When I execute the application I get this error message any suggestions on troubling shooting?
Server Error in '/XYZ' Application.
Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
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.IO.FileLoadException: Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
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.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs) +0
System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs) +38
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +571
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Boolean inherit) +37
Owin.Loader.DefaultLoader.SearchForStartupAttribute(String friendlyName, IList1 errors, Boolean& conflict) +106
Owin.Loader.DefaultLoader.GetDefaultConfiguration(String friendlyName, IList1 errors) +46
Owin.Loader.DefaultLoader.LoadImplementation(String startupName, IList1 errorDetails) +75
Owin.Loader.DefaultLoader.Load(String startupName, IList1 errorDetails) +21
Microsoft.Owin.Host.SystemWeb.OwinBuilder.GetAppStartup() +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +28
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +534
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +352
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Could not load file or assembly 'MvcSiteMapProvider, Version=4.6.22.0, Culture=neutral, PublicKeyToken=1923abe4657913cc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9947380
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261
Assuming you actually have the Nuget package installed, that error is most usually an issue with binding redirects in your Web.config. You can try to resolve the issue manually, by finding the appropriate binding redirect and making sure the version numbers are correct. I find it easier to just force remove the package and reinstall it. That will usually fix the problem:
> uninstall-package MvcSiteMapProvider.MVC4 -Force
> install-package MvcSiteMapProvider.MVC4
Make sure your Web.config is not open in your documents pane, or if it is, that you allow it to reload. If you save over it without refreshing from the filesystem after installing a Nuget package, you'll often bork things like binding redirects, leading to this issue.

ASP.NET MVC 4 Website won't start - Could not load type 'System.Reflection.AssemblyMetadataAttribute'

I deployed my ASP.NET MVC 4 web app to a Windows Server 2003 (IIS 6). But it will not start.
Originally I had developed the project for .NET 4.5, but had to rebuild it for .NET4 when I found out that .NET 4.5 is not supported on Windows Server 2003.
This meant removing all the third party references (with NuGet), changing the build target in project properties to .NET4, then adding the references back.
The references were to Ninject, EF and Automapper.
When I try to load a page I get the following error:
Could not load type 'System.Reflection.AssemblyMetadataAttribute' 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.Reflection.AssemblyMetadataAttribute' 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.Reflection.AssemblyMetadataAttribute' 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) +180
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken,
Type[] genericTypeArguments, Type[] genericMethodArguments) +192
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) +115
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule
decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount,
RuntimeType attributeFilterType, Boolean mustBeInheritable, IList
derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +426
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly
assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Type
attributeType, Boolean inherit) +64
WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly
assembly) +113
WebActivator.ActivationManager.RunActivationMethods() +216
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: Could not load type
'System.Reflection.AssemblyMetadataAttribute' from assembly 'mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'..]
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: Could not load type
'System.Reflection.AssemblyMetadataAttribute' from assembly 'mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9164848
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
+258
Any ideas?
EDIT: Website developed using VS2012
Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib
Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.

The service cannot be activated due to an exception during compilation

I have deployed WCF service on IIS 7 (Windows Server 2008), but I'm getting a strange error:
WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/31364015
Exception: System.ServiceModel.ServiceActivationException: The service '/WCFService.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'IHEC.WS.dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)). ---> System.Configuration.ConfigurationErrorsException: Could not load file or assembly 'IHEC.WS.dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) ---> System.IO.FileLoadException: Could not load file or assembly 'IHEC.WS.dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
File name: 'IHEC.WS.dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' ---> System.IO.FileLoadException: Could not load file or assembly 'IHEC.WS.dll' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
File name: 'IHEC.WS.dll'
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective)
--- End of inner exception stack trace ---
at System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective)
at System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory()
at System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai)
at System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig)
at System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir)
at System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors)
at System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory vdir, VirtualPath virtualDir, Boolean ignoreErrors)
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)
at System.Web.Compilation.BuildManager.GetCompiledCustomString(String virtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.GetCompiledCustomString(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
Process Name: w3wp
Process ID: 2616
The strange is, that the file IHEC.WS.dll is there in the bin directory.
Moving OP's own answer/comment to Answers
meanwhile I have solved this problem. When I deploy a project with
using Web Deployment Project and set 'Allow this precompiled site to
be updateble' it works fine. But I don't know why

Changing the web.config takes the WCF service down?

I have a simple WCF service hosted on IIS. Anytime I change the web.config file the service goes down and shows the following error:
Could not load file or assembly
'AutoMapper, Version=1.1.0.188,
Culture=neutral,
PublicKeyToken=be96cd2c38ef1005' or
one of its dependencies. Logon
failure: unknown user name or bad
password. (Exception from HRESULT:
0x8007052E)
To correct it, I need to delete all existing files and re-publish the WCF service. Re-publishing without deleting old files doesn't work, and neither does restarting the iis server.
Does anyone know why this happens? Or if there is an alternative to republishing the service to bring it back up? I am using IIS on Windows Server 2003, which I think is 6.0, and .Net framework 4.0
Further Error Info...
Assembly Load Trace: The following
information can be helpful to
determine why the assembly
'AutoMapper, Version=1.1.0.188,
Culture=neutral,
PublicKeyToken=be96cd2c38ef1005' could
not be loaded.
WRN: Assembly binding logging is
turned OFF. To enable assembly bind
failure logging, set the registry
value
[HKLM\Software\Microsoft\Fusion!EnableLog]
(DWORD) to 1. Note: There is some
performance penalty associated with
assembly bind failure logging. To turn
this feature off, remove the registry
value
[HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load
file or assembly 'AutoMapper,
Version=1.1.0.188, Culture=neutral,
PublicKeyToken=be96cd2c38ef1005' or
one of its dependencies. Logon
failure: unknown user name or bad
password. (Exception from HRESULT:
0x8007052E)]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName
fileName, String codeBase, Evidence
assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark&
stackMark, Boolean
throwOnFileNotFound, Boolean
forIntrospection, Boolean
suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName
fileName, String codeBase, Evidence
assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark&
stackMark, Boolean
throwOnFileNotFound, Boolean
forIntrospection, Boolean
suppressSecurityChecks) +39
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
assemblyRef, Evidence
assemblySecurity, StackCrawlMark&
stackMark, Boolean forIntrospection,
Boolean suppressSecurityChecks) +132
System.Reflection.RuntimeAssembly.InternalLoad(String
assemblyString, Evidence
assemblySecurity, StackCrawlMark&
stackMark, Boolean forIntrospection)
+144 System.Reflection.Assembly.Load(String
assemblyString) +28
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[]
baseAddresses) +208
System.ServiceModel.HostingManager.CreateService(String
normalizedVirtualPath) +1440
System.ServiceModel.HostingManager.ActivateService(String
normalizedVirtualPath) +44
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath) +615
[ServiceActivationException: The
service
'/Services/ClientLoginService.svc'
cannot be activated due to an
exception during compilation. The
exception message is: Could not load
file or assembly 'AutoMapper,
Version=1.1.0.188, Culture=neutral,
PublicKeyToken=be96cd2c38ef1005' or
one of its dependencies. Logon
failure: unknown user name or bad
password. (Exception from HRESULT:
0x8007052E).]
System.Runtime.AsyncResult.End(IAsyncResult
result) +679246
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +190
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication
context, String
routeServiceVirtualPath, Boolean
flowContext, Boolean ensureWFService)
+234 System.ServiceModel.Activation.HttpModule.ProcessRequest(Object
sender, EventArgs e) +355
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+148 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+75