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

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?

Related

Import method of windows security encryption algorithm is not working in hosting environment

I need to use RSA cryptography for encryption of data. I have used ImportPkcs8PrivateKey method of System.Security.Cryptography for importing private key. The code working fine in visual studio but only ImportPkcs8PrivateKey method is not working in hosting server. My Hosting server is windows 2019 and I have installed all hosting package.
var privateKeyBytes = Convert.FromBase64String(marchentPrivateKey);
int myarray;
var rsa = RSA.Create();
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out myarray);
return rsa;
The following Error trace is generated in hosted server
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
Actually its issue of IIS setting. Cryptographic Service Provider try to store a key for certificate in the user store and if a profile was not available, a cryptographic context was not available. By default IIS Load User Profile is false. See for more details
What exactly happens when I set LoadUserProfile of IIS pool?

InvalidSaml2BindingException: Not HTTP GET Method

I am using ITfoxtec.Identity.Saml2.MvcCore 4.0.7 with TestWebAppCore and TestIdPCore from GitHub ITfoxtec.
When I run this sample from Visual Studio I am not getting any errors and everything works fine. But when I deploy these samples to IIS 10 on Windows server 2019 then I get an error on testing SecurePage, see my error here below.
It looks like ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read method receives an POST request in the Sample program instead of GET.
Can you help me with this exception?
An unhandled exception occurred while processing the request.
InvalidSaml2BindingException: Not HTTP GET Method.
ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, string messageName, bool validateXmlSignature) in Saml2RedirectBinding.cs, line 151
Stack Query Cookies Headers Routing
InvalidSaml2BindingException: Not HTTP GET Method.
ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, string messageName, bool validateXmlSignature) in Saml2RedirectBinding.cs
throw new InvalidSaml2BindingException("Not HTTP GET Method.");
ITfoxtec.Identity.Saml2.Saml2Binding.ReadSamlRequest(HttpRequest request, Saml2Request saml2Request) in Saml2Binding.cs
{
TestIdPCore.Controllers.AuthController.ReadRelyingPartyFromLoginRequest(Saml2Binding binding) in AuthController.cs
return binding.ReadSamlRequest(Request.ToGenericHttpRequest(), new Saml2AuthnRequest(config))?.Issuer;
TestIdPCore.Controllers.AuthController.Login() in AuthController.cs
var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding));
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Kind Regards
Ed
I have not seen this error before I'm afraid. It looks like the SAML 2.0 Authn Request is send as POST instead of GET.
The samples for ITfoxtec Identity SAML handels SAML 2.0 Authn Request with Saml2RedirectBinding by default. Do the TestWebAppCore.AuthController Login method in your case use Saml2RedirectBinding?

InvalidOperationException: Unable to resolve service for type '*Models.LandingPageContext' while attempting to activate Controller'

I have a database named "LandingPage", and using this command i have mapped the database tables inside my asp.net mvc core:-
Scaffold-DbContext "Server=(localdb)\ProjectsV13;Database=LandingPage;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Then i added a controller and chose one of the models, but when i try access the controller i got this exception inside the web browser:-
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Stack Query Cookies Headers Routing
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
The DbContext needs to be registered as a service in Startup.cs so that it can be injected into the controller in its constructor:
Startup.cs:
services.AddDbContext<LandingPageContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
QuestionsController.cs:
public class QuestionsController: Controller
{
public QuestionsController(LandingPageContext dbContext)
{
}
}
More information in Dependency injection in ASP.NET Core.

Why won't my MVC4 HandleErrorAttribute work?

I'm converting an MVC3 web project to MVC4. I created a ElmahHandleErrorAttribute that inherits from HandleErrorAttribute that worked fine in MVC3 and also works fine on my local dev machine, but it throws the following exception in the test environment...
[InvalidOperationException: The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.]
System.Web.Mvc.GlobalFilterCollection.ValidateFilterInstance(Object instance) +110
System.Web.Mvc.GlobalFilterCollection.AddInternal(Object filter, Nullable`1 order) +17
System.Web.Mvc.GlobalFilterCollection.Add(Object filter) +12
Home2Me.MvcApplication.RegisterGlobalFilters(GlobalFilterCollection filters) in c:\###\Home2Me\Global.asax.cs:16
Home2Me.MvcApplication.Application_Start() in c:\###\Home2Me\Global.asax.cs:118
[HttpException (0x80004005): The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9249709
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +131
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253
[HttpException (0x80004005): The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9164336
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256
There isn't really anything special about the class. It's pretty close to the standard one for Elmah.
public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
/// <summary>
/// Called when an exception occurs.
/// </summary>
/// <param name="context"></param>
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (!context.ExceptionHandled) return; // if unhandled, will be logged anyhow
var e = context.Exception;
HandleException(e);
}
... (code snipped for brevity) ...
}
And here is the code that registers the filter in Global.asax.cs...
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ElmahHandleErrorAttribute());
}
The filter is defined in a separate assembly that is also updated to MVC4. I have multiple projects that use this filter. One of them works fine in the test environment, and another has this same exact issue.
Any ideas on what might be wrong? I'm fairly confident that all the MVC3 references have been updated correctly in the project, including the web.config files in both the root and views directory. It does work locally and I uninstalled MVC3 and deleted all the "extra" MVC3 dlls lying around.
I believe I found an answer. I added a runtime section in the root web.config file to convert MVC3 references to MVC4.
<configuration>
... (snipped for brevity) ...
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I would rather fix whatever it is that is referencing MVC3, but I can't figure out what that might be. This will have to be a good enough answer for now.

Castle Windsor Dynamic Assembly Bug?

I'm using Castle Windsor 3.1.0 in an ASP .NET 4 MVC application, which is giving me an exception in the Application_Start event when container.Register is called.
The exception is "The invoked member is not supported in a dynamic assembly.". Here's the stack trace:
[NotSupportedException: The invoked member is not supported in a dynamic assembly.]
System.Reflection.Emit.InternalAssemblyBuilder.GetExportedTypes() +56
Castle.Core.Internal.ReflectionUtil.GetAvailableTypes(Assembly assembly, Boolean includeNonExported) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\Core\Internal\ReflectionUtil.cs:165
Castle.MicroKernel.Registration.FromAssemblyDescriptor.<SelectedTypes>b__0(Assembly a) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\MicroKernel\Registration\FromAssemblyDescriptor.cs:56
System.Linq.<SelectManyIterator>d__14`2.MoveNext() +238
Castle.MicroKernel.Registration.FromDescriptor.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\MicroKernel\Registration\FromDescriptor.cs:160
Castle.MicroKernel.Registration.BasedOnDescriptor.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\MicroKernel\Registration\BasedOnDescriptor.cs:530
Castle.MicroKernel.DefaultKernel.Register(IRegistration[] registrations) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\MicroKernel\DefaultKernel.cs:506
Castle.Windsor.WindsorContainer.Register(IRegistration[] registrations) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\Windsor\WindsorContainer.cs:483
ProductX.Web.Windsor.Installers.ControllerInstaller.Install(IWindsorContainer container, IConfigurationStore store) in C:\TeamProjects\CompanyX.ProductX\Mainline\Admin\ProductX.Web\Windsor\Installers\ControllerInstaller.cs:24
Castle.Windsor.Installer.AssemblyInstaller.Install(IWindsorContainer container, IConfigurationStore store) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\Windsor\Installer\AssemblyInstaller.cs:56
Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\Windsor\WindsorContainer.cs:319
Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers) in c:\BuildAgent\work\5b096cace0fecb1f\src\Castle.Windsor\Windsor\WindsorContainer.cs:452
ProductX.Web.MvcApplication.InitializeWindsor() in C:\TeamProjects\CompanyX.ProductX\Mainline\Admin\ProductX.Web\Global.asax.cs:41
ProductX.Web.MvcApplication.Application_Start() in C:\TeamProjects\CompanyX.ProductX\Mainline\Admin\ProductX.Web\Global.asax.cs:25
[HttpException (0x80004005): The invoked member is not supported in a dynamic assembly.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9171773
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +131
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253
[HttpException (0x80004005): The invoked member is not supported in a dynamic assembly.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256
Here's how I'm calling Register:
container.Register(Classes.FromThisAssembly().BasedOn<IController>().LifestyleTransient());
When I build the application in Debug mode, it's fine. When I build in Release mode, the exception above occurrs. I can't find anything about this error through Google. My suspicion is that some .NET 4 restrictions were introduced with how reflection is done on dynamic assemblies, which is being introduced in this situation as a Release build optimisation.
Any idea anyone?
Looks like you're getting a dynamic assembly being emitted (somehow). Try adding a filter to ignore dynamic assemblies. This should work:
container.Register(Classes.FromThisAssembly().Where(t => !t.Assembly.IsDynamic).BasedOn<IController>().LifestyleTransient());