Setting HttpRuntime.WebObjectActivator makes HttpApplication.InitModulesCommon throw a NullReferenceException.
I'm setting it in my Application_Start and setting it back to null makes the error go away so its consistent.
The stacktrace is as follows
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.HttpApplication.InitModulesCommon() +166
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +792
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +153
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +327
My best guess is that its this line which is failing https://referencesource.microsoft.com/#system.web/HttpApplication.cs,2337 due to all modules being resolved by the WebObjectActivator and therefor returning null if they arent registered as seen here https://referencesource.microsoft.com/#system.web/ModulesEntry.cs,62 and here https://referencesource.microsoft.com/#system.web/HttpRuntime.cs,3388
By is that really the case... ? Is it really the responsibility of the activator to instantiate objects which isn't registered as well?
Reading the answer to this question unfortunately confirms that whoever cooked up HttpRuntime.WebObjectActivator wasn't thinking it through
Wiring up Simple Injector in WebForms in .NET 4.7.2
Related
I have made an ASP.NET Core (.Net 5) Web API which works perfectly fine on my local machine. And actually all contorllers except one work fine too. When I make a Post Request to my DataStoreController I get the following exception:
System.BadImageFormatException: Bad binary signature. (0x80131192)
at
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(RuntimeMethodHandleInternal
method) at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type
delegateType, Object target) at
System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression
lambda) at System.Linq.Expressions.Expression`1.Compile() at
Microsoft.Extensions.Internal.ObjectMethodExecutor.GetExecutor(MethodInfo
methodInfo, TypeInfo targetTypeInfo) at
Microsoft.Extensions.Internal.ObjectMethodExecutor..ctor(MethodInfo
methodInfo, TypeInfo targetTypeInfo, Object[] parameterDefaultValues)
at
Microsoft.Extensions.Internal.ObjectMethodExecutor.Create(MethodInfo
methodInfo, TypeInfo targetTypeInfo, Object[] parameterDefaultValues)
at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerCache.GetCachedResult(ControllerContext
controllerContext) at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext
actionContext) at
Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory.<>c__DisplayClass7_0.b__0(HttpContext
context) at
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext
httpContext)
--- End of stack trace from previous location --- at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext) at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider) at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)
I have tried what would happen if I made the Method inside the Controller empty and just return null - but still the same error. The only differnce package-wise to the other controllers is that the DataStoreController uses the Stackexchange.Redis NuGet Package.
My gut feeling tells me that this is a weird Azure Bug, but I would love to get some opinions/advices/answers from you.
Okay okay. I have kind of found a solution.
I stopped and started the App Service and now everything works. This actually might be a weird Azure Issue.
I (noob to light inject mvc) am using LightInject MVC in my asp.mvc 4 app with great results except an occasional exception. Now I am seeing it in pre-production. The exception is: System.InvalidOperationException: Attempt to create a scoped instance without a current scope.
My app start code is:
var container = new LightInject.ServiceContainer();
container.RegisterControllers();
container.RegisterAssembly(typeof(AppDDD.RegisterMe).Assembly, () => new PerScopeLifetime());
... scoped registrations
container.EnableMvc();
I get the error with a stack trace like:
System.InvalidOperationException: An error occurred when trying to
create a controller of type 'MvcAPP.Controllers.HomeController'. Make
sure that the controller has a parameterless public constructor. --->
System.InvalidOperationException: Attempt to create a scoped instance
without a current scope. at
LightInject.PerScopeLifetime.GetInstance(Func1 createInstance, Scope
scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.<>c__DisplayClass40.<WrapAsFuncDelegate>b__3f()
at LightInject.PerRequestLifeTime.GetInstance(Func1 createInstance,
Scope scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.TryGetInstance(Type serviceType) at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) --- End of inner exception
stack trace --- at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) at
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
I have created a couple of small test ASP MVC projects to isolate the exception with no success.
The Controllers are scoped per instance, and all the objects with in each instance are designated PerScopeLifetime.
Is there a tweak I can make, or should I stop using PerScopeLifetime? I must have scoped lifetimes for my EF contexts.
The exception is thrown before my controllers finish constructing, so it appears.
I would like you to know that the issue has been resolved and getting the latest and greatest from NuGet should fix your problem.
Best regards
Bernhard Richter
I'm using Patterns and Practices' Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here's my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here's the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I'm not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn't seem to help and why would it be needed now and not before? So I'm stumped. This is my first attempt at using Dependency Injection, so it's probably something basic. I'm just not seeing what, though.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.
This is what i use to implement an Dependency Injection in my MVC3 project,
public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel _ninjectKernel;
public NinjectControllerFactory()
{
_ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)_ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
_ninjectKernel.Bind<IUserRepository>().To<UserRepository>().InSingletonScope();
}
}
but i have a huge problem i want to use an Generic Handler an ".ashx" to implement my logic.
But i get an exception because the httphandler is not a Controller.
here is the exception:
Server Error in '/' Application.
The IControllerFactory 'Infrastructure.NinjectFactory.NinjectControllerFactory' did not return a controller for the name 'registercustomer.ashx'.
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.InvalidOperationException: The IControllerFactory 'Infrastructure.NinjectFactory.NinjectControllerFactory' did not return a controller for the name 'registercustomer.ashx'.
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:
[InvalidOperationException: The IControllerFactory 'Infrastructure.NinjectFactory.NinjectControllerFactory' did not return a controller for the name 'registercustomer.ashx'.]
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +422803
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8971636
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.547
Now is the question: How do i implement the work around this bug, to me to be able to an HttpHandler and still remain using the Ninject in my project?
Thanks in advance.
Due to the HttpHandler being created by the framework and there is no hook or factory method to intercept the creation of the ashx file, ninject is not able to create this object.
However you can use service locator calls or property injection from the ashx to request dependancies from the ashx code. But as far as I know, the ashx must have a default constructor, and you can then either resolve the dependancies from inside the constructor (or anywhere really) via service locator (less preferred method) or via property injection simply like this:
public class Handler
{
[Inject]
public IService Service { get; set; }
}
EDIT: also, to tell mvc to not process the ashx file you need to add this to ignore the route:
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
I have problem. Locally everything works fine but in the production server it always throws exception 'Response is not available in this context'. What can be the problem? I've noticed that a lot of people experience this problem due to some changes of global.asax. Here is the code of global.asax, the part related to application start.
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
Application["SystemUser"] = TUser.GetUserByIdentifier("system").UID;
InitializeSolrInstances();
SearchIndexer.DoIndex();
StartRatingTimer();
SolrManager.RecalculateMostRequested();
}
private static void InitializeSolrInstances() {
SolrConfigurationManager.InitSolrConnection<OfferItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/offer");
SolrConfigurationManager.InitSolrConnection<SavedQueryItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/savedquery");
SolrConfigurationManager.InitSolrConnection<TopProductsPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topproducts");
SolrConfigurationManager.InitSolrConnection<TopSellersPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topsellers");
SolrConfigurationManager.InitSolrConnection<MostRequestedItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/mostrequested");
SolrConfigurationManager.InitSolrConnection<MostRequestedQuery>(Resources.ApplicationResources.SolrServiceURL + "/requestedquery");
}
private void StartRatingTimer() {
_LastRatingRenewedTime = DateTime.Now;
DateTime CurrentTime = DateTime.Now;
DateTime StartTime = new DateTime(2011, 1, 1);
GlobalSettings.ReIndexMainSolrCores(StartTime, CurrentTime);
Timer OfferAndUserRatingRenewerTimer = new Timer() {
/*Timer interval for 24 hours*/
Interval = 24 * 60 * 60 * 1000, Enabled = true };
OfferAndUserRatingRenewerTimer.Elapsed += new ElapsedEventHandler(OfferAndUserRatingRenewerTimer_Elapsed);
}
public void OfferAndUserRatingRenewerTimer_Elapsed(Object Sender, ElapsedEventArgs e) {
GlobalSettings.ReIndexMainSolrCores(_LastRatingRenewedTime, e.SignalTime);
_LastRatingRenewedTime = e.SignalTime;
}
I do not use Response or Request properties of HttpContext at all. Neither in global asax itself, nor within the methods to be called. Help me.
That what it shows.
`
Server Error in '/' Application.
Response is not available in this context.
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.Web.HttpException: Response is not available in this context.
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:
[HttpException (0x80004005): Response is not available in this context.]
System.Web.Util.HttpEncoder.get_Current() +11406684
System.Web.HttpUtility.UrlEncode(String str, Encoding e) +137
SolrNet.Impl.SolrConnection.<Get>b__0(KeyValuePair`2 input) +89
SolrNet.Utils.<Select>d__1a`2.MoveNext() +612
SolrNet.Utils.Func.Reduce(IEnumerable`1 source, TResult startValue, Accumulator`2 accumulator) +393
SolrNet.Impl.SolrConnection.Get(String relativeUrl, IEnumerable`1 parameters) +908
SolrNet.Impl.SolrQueryExecuter`1.Execute(ISolrQuery q, QueryOptions options) +195
SolrNet.Impl.SolrBasicServer`1.Query(ISolrQuery query, QueryOptions options) +176
SolrNet.Impl.SolrServer`1.Query(ISolrQuery query, QueryOptions options) +176
TebeComSearchEngine.SolrManager.RecalculateMostRequested() in SolrManager.cs:77
TebeCom.MvcApplication.Application_Start() in Global.asax.cs:101
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4043621
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +352
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11612256
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4842149`
'Response is not available in this context'. What can be the problem?
You are running this in IIS7 Integrated Application Pool mode instead of Classic mode. In Integrated mode you don't have access to the HttpResponse in Application_Start any any attempt to access it will blow.
Here's a blog post which covers a similar situation but with the HttpRequest.
After a lot of digging and looking around the SolrNet code, they don't appear to be doing anything wrong. Also, as Darin pointed out in an indirect manner, HttpUtility.UrlEncode should work fine in code without a HttpContext, such as a console application, and it does.
However, as VinayC pointed out in his comment on that answer of Darin's:
Actually, it appears to be a bug. From
reflector, actual code appears to be
"if (null != current && null !=
current.Response && ...)" where
current is current http context. Issue
here is that Response getter throws an
exception, instead of returning null
Instead of throwing that overly descriptive exception (no doubt they were trying to be helpful), they should have just returned null and let null reference exceptions happen. In this case, they were simply checking for nulls, so the exception wouldn't have happened anyway! I'll report it as a bug if it hasn't been already.
Unfortunately, what this means to you is that you have pretty much no choice but to run in Classic mode. Technically you could put the call to TebeComSearchEngine.SolrManager.RecalculateMostRequested() in a thread that you spawn in application_start and delay its execution until after the app finishes starting. As far as I know, there is no surefire way to programmatically signal the end of the application starting so, that approach may be a little messy.
If you're up for it though, you could probably get that delayed startup mechanism implemented. Compared to punishing the first visitor to the site, it doesn't seem too bad.
This was discussed about a month ago in the SolrNet mailing list.
It's a regression in ASP.NET 4, here's a mention of this bug.
A future release of SolrNet will replace System.Web.HttpUtility.UrlEncode to work around this bug. (or if you really need this, why not fork the source code and fix it?)
EDIT: I just fixed this.